List
- ArrayList
- 隨機存取效率高(get & set)
- 插入和刪除較慢(除末尾)
- LinkedList
- 最優(yōu)順序存取
- 插入和刪除較快
- 隨機存取較慢
- larger feature set?更多的屬性?
ArrayList
Method
構造方法
共三種
- 默認構造方法, 大小指定為10
public ArrayList() {
this(10);
}
- 指定大小構造方法
public ArrayList(int initialCapacity) {
super();
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal Capacity: "+ initialCapacity);
this.elementData = (E[])new Object[initialCapacity];
}
- 指定集合內容的構造方法
public ArrayList(Collection<? extends E> c) {
elementData = c.toArray();
size = elementData.length;
// c.toArray might (incorrectly) not return Object[] (see 6260652)
if (elementData.getClass() != Object[].class)
elementData = Arrays.copyOf(elementData, size, Object[].class);
}
######常用方法
- ```contains(Object o)``` 判斷是否包含某元素,使用equals對比
``` java
boolean isContain = list.contains(object);
-
remove(Object o)刪除指定對象,參數(shù)為對象的引用
list.remove(reference);
-
indexOf(Object o)獲取指定對象的位置,參數(shù)為對象的引用
// 返回-1代表未發(fā)現(xiàn)元素
int index = list.indexOf(reference);
-
subList(int from, int to)獲取子集list.subList(3, 9);
這里要注意,操作子集,會對原List進行影響。
如要對子集進行add/remove等操作,可以這樣:
``` java
List<Integer> sub = new ArrayList<Integer>(list.subList(3, 9));
-
containsAll(Collection<?> c)判斷列表中是否包含指定collection的所有元素
list.containsAll(sub);
-
removeAll(Collection<?> c)批量刪除指定的元素
list.removeAll(sub);
-
set(int index, E element)替換index位置的元素,并返回之前的元素
list.set(9, e);
-
toArray(), toArray(T[] t)List轉化為數(shù)組,一般用第二個
String[] array = new String[list.size()];
list.toArray(array);
擴容
擴容后的大小為原大小的1.5倍加1:
int newCapacity = (oldCapacity * 3)/2 + 1;
To Be Continue...