List
List是可以放重覆的資料,新增的資料是有順序。
每一筆資料都是有索引。
List方法
get
參數為索引,取得某個位置的物件。
1
E get(int index);
程式碼
1
2
3
4
List list = new ArrayList();
list.add(10);
list.add(true);
System.out.println(list.get(0));
10
addAll
語法
boolean addAll(int index, Collection<? extends E> c);
在index索引位置,插入新的集合。
1
2
3
4
5
6
7
8
List list = new ArrayList();
list.add(10);
list.add(true);
list.add("str");
List list2 = new ArrayList();
list2.add("test");
list.addAll(1, list2);
System.out.println(list);
[10, test, true, str]
indexOf
尋找物件所在位置。
1
2
3
4
5
6
List list = new ArrayList();
list.add(10);
list.add(true);
list.add("str");
int find = list.indexOf("str");
System.out.println(find);
2
lastIndexOf
找到物件最後的索引位置
1
2
3
4
5
6
7
8
List list = new ArrayList();
list.add(10);
list.add(true);
list.add("str");
list.add("str");
list.add("str");
int find = list.lastIndexOf("str");
System.out.println(find);
4
remove
移除某個索引的物件。
1
2
3
4
5
6
7
8
List list = new ArrayList();
list.add(10);
list.add(true);
list.add("str");
list.add("str");
list.add("str");
list.remove(4);
System.out.println(list);
[10, true, str, str]
set修改
索引一定要小於集合的大小,不然會有例外。
1
2
3
4
5
6
7
8
List list = new ArrayList();
list.add(10);
list.add(true);
list.add("str");
list.add("str");
list.add("str");
list.set(4, "Tom");
System.out.println(list);
[10, true, str, str, Tom]
subList
取得子集合,從fromIndex到(toIndex - 1),注意!不包含toIndex。
1
List<E> subList(int fromIndex, int toIndex);
1
2
3
4
5
6
7
8
List list = new ArrayList();
list.add(10);
list.add(true);
list.add("str");
list.add("str");
list.add("str");
List sub = list.subList(0, 2)
System.out.println(sub);
[10, true]
ArrayList
- 實際上程式碼是陣列。
- 不是執行緒安全。
以下是ArrayList.add(),傳回值前面「沒有synchronized」。
1
2
3
4
5
public boolean add(E e) {
modCount++;
add(e, elementData, size);
return true;
}
以下是Vector.add(),傳回值前面「有synchronized」。
1
2
3
4
5
public synchronized boolean add(E e) {
modCount++;
add(e, elementData, elementCount);
return true;
}