1. List
List集合繼承于Collection, public interface List<E> extends Collection<E>
常用的List集合應該是LinkedList以及ArrayList的實作,顧名思義,分别代表連結清單實作以及數組實作,那麼對應的性能方面的差別就是連結清單和數組的差別
常用方法包括:
-
:檢視list大小size()
-
:添加元素add(E element)
-
:添加元素到指定位置add(int index, E element)
-
:添加集合中所有元素到清單末尾addAll(Collection<? entends E> c)
-
:添加元素到指定位置addAll(int index, Collection<? entends E> c)
-
:檢視是否包含某個元素contains(Object o)
-
:傳回一個由list元素構成的數組toArray()
-
:擷取元素get(int index)
-
:替換指定位置的元素set(int index, E element)
-
或remove(Object o)
:移除元素remove(int index)
測試小程式
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
public class ListTest {
public static void main(String[] args) {
List<Integer> linkedList = new LinkedList<>();
List<Integer> arrayList = new ArrayList<>();
// 添加元素
for(int i=0; i<10; ++i){
linkedList.add(i);
arrayList.add(i);
}
// 列印元素
System.out.println("LinkedList: ");
for(int e : linkedList){
System.out.print(e);
System.out.print(" ");
}
System.out.println();
System.out.println("ArrayList: ");
for(int e : arrayList){
System.out.print(e);
System.out.print(" ");
}
System.out.println();
// 這裡隻用一個List作示例,另外一個是一樣的,隻不過效率不同
// 指定位置添加元素
linkedList.add(1, 100);
System.out.println("Add 100 to the second loc LinkedList: ");
for(int e : linkedList) {
System.out.print(e);
System.out.print(" ");
}
System.out.println();
// 更換元素
linkedList.set(0, 99);
System.out.println("Modify the first element LinkedList: ");
for(int e : linkedList) {
System.out.print(e);
System.out.print(" ");
}
System.out.println();
// 移除元素
linkedList.remove(1);
System.out.println("Remove the second element: ");
for(int e : linkedList) {
System.out.print(e);
System.out.print(" ");
}
System.out.println();
System.out.println("List contains 3? " + linkedList.contains(3));
Object[] array = linkedList.toArray();
System.out.println("toArray: ");
System.out.println(Arrays.toString(array));
System.out.println("test done...");
}
}
測試結果
LinkedList:
0 1 2 3 4 5 6 7 8 9
ArrayList:
0 1 2 3 4 5 6 7 8 9
Add 100 to the second loc LinkedList:
0 100 1 2 3 4 5 6 7 8 9
Modify the first element LinkedList:
99 100 1 2 3 4 5 6 7 8 9
Remove the second element:
99 1 2 3 4 5 6 7 8 9
List contains 3? true
toArray:
[99, 1, 2, 3, 4, 5, 6, 7, 8, 9]
test done...