一、ArrayList解析

1.1 基本常量和變量
首先明確一點,ArrayList采用Object對象數(shù)組實現(xiàn)
private static final long serialVersionUID = 8683452581122892189L;
/**
* Default initial capacity.
* ArrayList初始化默認(rèn)容量大小為10,見無參構(gòu)造函數(shù)。
*/
private static final int DEFAULT_CAPACITY = 10;
/**
* Shared empty array instance used for empty instances.
* 空實例共享的空數(shù)組實例。
*/
private static final Object[] EMPTY_ELEMENTDATA = {};
/**
* Shared empty array instance used for default sized empty instances. We
* distinguish this from EMPTY_ELEMENTDATA to know how much to inflate when
* first element is added.
* 默認(rèn)大小的空實例共享的空數(shù)組實例。將它與EMPTY_ELEMENTDATA區(qū)分開,以便確定當(dāng)添加了第一個成員之后擴(kuò)充多大。
*/
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
/**
* The array buffer into which the elements of the ArrayList are stored.
* The capacity of the ArrayList is the length of this array buffer. Any
* empty ArrayList with elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA
* will be expanded to DEFAULT_CAPACITY when the first element is added.
* ArrayList成員存儲在這個數(shù)組緩沖區(qū)中。
* 容量大小是這個緩沖區(qū)的長度,任何elementDate==DEFAULTCAPACITY_EMPTY_ELEMENTDATA的空ArrayList
* 在添加第一個成員時都會擴(kuò)充到DEFAULT_CAPACITY大小,即容量為10。
*/
transient Object[] elementData; // non-private to simplify nested class access
/**
* The size of the ArrayList (the number of elements it contains).
* ArrayList的大小,注意是實際包含的成員個數(shù)。
* @serial
*/
private int size;
1.2 構(gòu)造方法
1)無參構(gòu)造函數(shù)
/**
* Constructs an empty list with an initial capacity of ten.
* 構(gòu)造一個初始容量為10的空list。
*/
public ArrayList() {
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
任何elementDate==DEFAULTCAPACITY_EMPTY_ELEMENTDATA的空ArrayList,在添加第一個成員時都會擴(kuò)充到DEFAULT_CAPACITY大小,即容量為10(詳見add方法)
2)帶指定初始容量參數(shù)的構(gòu)造函數(shù)
/**
* Constructs an empty list with the specified initial capacity.
* 構(gòu)造一個指定了初始容量的空list。
* @param initialCapacity the initial capacity of the list
* initialCapacity指定list的初始容量
* @throws IllegalArgumentException if the specified initial capacity
* is negative
* 當(dāng)指定容量值為負(fù)值時,拋出IllegalArgumentException異常
*/
public ArrayList(int initialCapacity) {
if (initialCapacity > 0) {
this.elementData = new Object[initialCapacity];
} else if (initialCapacity == 0) {
this.elementData = EMPTY_ELEMENTDATA;
} else {
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
}
}
當(dāng)指定的初始容量值大于零時,新建一個大小為initialCapacity的Object數(shù)組,并賦 elementData;
當(dāng)指定的初始容量值為零時,將 EMPTY_ELEMENTDATA賦給elementData。
1.3 自動擴(kuò)容機(jī)制與add方法
ArrayList底層是通過Object數(shù)組實現(xiàn)的。數(shù)組的特性是大小固定的,當(dāng)ArrayList 中的成員數(shù)量超過了capacity后,就需要分配一個更大的數(shù)組,并將原來的成員復(fù)制到新的數(shù)組中
ArrayList中有兩個大小概念。capacity和size,capacity就是底層Object數(shù)組的length,表示能容納的最大成員數(shù);size則表示已經(jīng)存儲的成員數(shù),可以通過size()函數(shù)獲取
1) ArrayList擴(kuò)容的相關(guān)方法:
/**
* Increases the capacity of this <tt>ArrayList</tt> instance, if
* necessary, to ensure that it can hold at least the number of elements
* specified by the minimum capacity argument.
* 如果需要,函數(shù)增加ArrayList的容量,以確保至少可以容納minCapacity指定的成員數(shù)量。
* @param minCapacity the desired minimum capacity
*/
public void ensureCapacity(int minCapacity) {
int minExpand = (elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA)
// any size if not default element table
? 0
// larger than default for default empty table. It's already
// supposed to be at default size.
: DEFAULT_CAPACITY;
if (minCapacity > minExpand) {
ensureExplicitCapacity(minCapacity);
}
}
private void ensureCapacityInternal(int minCapacity) {
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
}
ensureExplicitCapacity(minCapacity);
}
private void ensureExplicitCapacity(int minCapacity) {
modCount++;
// overflow-conscious code
//如果需要的最小容量比數(shù)組的長度大,那么就調(diào)用grow()來擴(kuò)容。(當(dāng)添加第11個元素時minCapacity為11,而數(shù)組長度為10,就需要擴(kuò)容了)
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
當(dāng)確定將要擴(kuò)容時,ensureExplicitCapacity()方法中調(diào)用的grow()方法,正是這個方法實現(xiàn)了擴(kuò)容:
/**
* Increases the capacity to ensure that it can hold at least the
* number of elements specified by the minimum capacity argument.
*
* @param minCapacity the desired minimum capacity
*/
private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;
int newCapacity = oldCapacity + (oldCapacity >> 1);
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;
if (newCapacity - MAX_ARRAY_SIZE > 0)
newCapacity = hugeCapacity(minCapacity);
// minCapacity is usually close to size, so this is a win:
elementData = Arrays.copyOf(elementData, newCapacity);
}
當(dāng)minCapacity大于ArrayList中的capacity時,就將數(shù)組的長度擴(kuò)充到原來的1.5倍,如果這個值還是小于minCapacity,就取minCapacity作為新的capacity。
擴(kuò)容完成后,調(diào)用copyOf()方法將成員復(fù)制到新數(shù)組中
public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) {
@SuppressWarnings("unchecked")
T[] copy = ((Object)newType == (Object)Object[].class)
? (T[]) new Object[newLength]
: (T[]) Array.newInstance(newType.getComponentType(), newLength);
System.arraycopy(original, 0, copy, 0,
Math.min(original.length, newLength));
return copy;
}
2)add操作
ArrayList的add操作都調(diào)用了上面的ensureCapacityInternal(),先保證ArrayList的capacity足夠大(至少為size+1),所以可能發(fā)生了數(shù)組的復(fù)制,也可能沒有發(fā)生。
所有的add相關(guān)的方法都修改了size的值,因此modCount值也會增加。
- 在ArrayList末尾添加一個成員
public boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
- 檢查數(shù)組的容量是否足夠
夠:直接添加
不夠: 擴(kuò)容到原來的1.5倍;擴(kuò)容后,如果容量還是小于minCapacity,就將容量擴(kuò)充為minCapacity
- 在指定位置插入一個成員
/**
* Inserts the specified element at the specified position in this
* list. Shifts the element currently at that position (if any) and
* any subsequent elements to the right (adds one to their indices).
*
* @param index index at which the specified element is to be inserted
* @param element element to be inserted
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
public void add(int index, E element) {
rangeCheckForAdd(index);
ensureCapacityInternal(size + 1); // Increments modCount!!
System.arraycopy(elementData, index, elementData, index + 1,
size - index);
elementData[index] = element;
size++;
}
這個方法在index的位置插入成員element:
先調(diào)用 rangeCheckForAdd 對index進(jìn)行界限檢查;然后調(diào)用 ensureCapacityInternal 方法保證capacity足夠大;再將從index開始之后的所有成員后移一個位置;將element插入index位置;最后size加1。
-remove()方法
public E remove(int index) {
rangeCheck(index);
modCount++;
E oldValue = elementData(index);
int numMoved = size - index - 1;
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
elementData[--size] = null; // clear to let GC do its work
return oldValue;
}
- 檢查下標(biāo)
- 刪除元素
- 計算出移動的次數(shù),移動
- 設(shè)置最后的位置為null,讓GC回收
1.4 get方法
- 檢查角標(biāo)
- 返回元素
private void rangeCheck(int index) {
if (index >= size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
E elementData(int index) {
return (E) elementData[index];
}
1.5 set方法
- 檢查角標(biāo)
- 替代元素
- 返回舊值
public E set(int index, E element) {
rangeCheck(index);
E oldValue = elementData(index);
elementData[index] = element;
return oldValue;
}
1.7 細(xì)節(jié)說明
ArrayList是基于動態(tài)數(shù)組實現(xiàn)的,在增刪時候,需要數(shù)組的拷貝復(fù)制。
ArrayList的默認(rèn)初始化容量是10,每次擴(kuò)容時候增加原先容量的一半,也就是變?yōu)樵瓉淼?.5倍
刪除元素時不會減少容量,若希望減少容量則調(diào)用trimToSize()
它不是線程安全的。它能存放null值
它是不同步的
ize、isEmpty、get、set、iterator和listIterator方法都以固定時間運行,時間復(fù)雜度為O(1)。add和remove方法需要O(n)時間。與用于LinkedList實現(xiàn)的常數(shù)因子相比,此實現(xiàn)的常數(shù)因子較低
二、 Vector與ArrayList的區(qū)別
Vector是JDK1.2的類,也是基于動態(tài)數(shù)組實現(xiàn)的,與ArrayList最大的區(qū)別就是它是線程安全的,主要是因為它的方法上都加了synchronized關(guān)鍵字(但是也不怎么用這個)。
如果想要ArrayList實現(xiàn)同步,可以使用Collections的方法: List list= Collections.synchronizedList(new ArrayList(...));
還有一個區(qū)別是:ArrayList擴(kuò)容是在原來的基礎(chǔ)上拓展0.5倍,但是Vector是拓展1倍
LinkedList

LinkedList底層是雙向鏈表

變量:

四、 小結(jié)
ArrayList:
- 底層實現(xiàn)是數(shù)組,查詢快增刪慢,線程不安全,效率高
- 默認(rèn)初始容量是10,每次以1.5倍擴(kuò)容
- 數(shù)組拷貝的native方法又熱(c/c++實現(xiàn))
LinkedList:
- 底層實現(xiàn)是雙向鏈表,查詢慢增刪快,線程不安全,效率高
Vector:
- 底層是數(shù)組,底層實現(xiàn)是數(shù)組,查詢快增刪慢,線程安全,效率低(Vector所有方法都是同步)
- 兩倍擴(kuò)容
參考: