Java容器——ArrayList(Java9 )原始碼解析
ArrayList是一種常用List型別實現,也是Java集合中的的常用型別,以遍歷查詢效能優異著稱,繼承關係如下:
可見ArrayList實現了Cloneable,Serializable,RandomAcess和List介面,繼承了AbstractList抽象類,簡而言之,ArrayList是一個實現了可複製,可序列化,支援快速隨機訪問的List型別。這裡最重要的是實現了List的介面,包括初始化,新增,查詢,刪除,銷燬等函式,具體如何實現,請見下文分析。
一 類成員變數
/**
* List預設初始化長度
*/
private static final int DEFAULT_CAPACITY = 10;
/**
* 儲存ArrayList資料的陣列
*/
transient Object[] elementData;
/**
* List的實際長度
*/
private int size;
/**
* ArrayList最大長度
*/
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
這裡列出了三個重要的變數,具體釋義見註釋。ArrayList在初始化時預設為空的陣列,當首個元素加入到List中時,長度擴容到10。size是陣列的實際容量,也即是List的大小,初始化為0。elementData是Object型別的陣列,也是實際存放資料的陣列。以Object作為陣列元素使得List可以有效支援泛型。這裡有一點需要注意,既然elementData用來存放元素,那為何不使用elementData.length而是使用size這一變數作為ArrayList的長度呢?在下文中會結合使用進行說明。
二 函式解析
1 建構函式
/**
* Constructs an empty list with the specified initial capacity.
*
* @param initialCapacity the initial capacity of the list
* @throws IllegalArgumentException if the specified initial capacity
* is negative
*/
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);
}
}
/**
* Constructs an empty list with an initial capacity of ten.
*/
public ArrayList() {
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
/**
* Constructs a list containing the elements of the specified
* collection, in the order they are returned by the collection's
* iterator.
*
* @param c the collection whose elements are to be placed into this list
* @throws NullPointerException if the specified collection is null
*/
public ArrayList(Collection<? extends E> c) {
elementData = c.toArray();
if ((size = elementData.length) != 0) {
// defend against c.toArray (incorrectly) not returning Object[]
// (see e.g. https://bugs.openjdk.java.net/browse/JDK-6260652)
if (elementData.getClass() != Object[].class)
elementData = Arrays.copyOf(elementData, size, Object[].class);
} else {
// replace with empty array.
this.elementData = EMPTY_ELEMENTDATA;
}
}
建構函式有三個:
- 無參建構函式:elementData初始化為空陣列,此時size預設為0。
- 初始化長度建構函式:elementData擴容為指定長度的未初始化陣列。注意這裡size並沒有被設定為指定長度,此時elementData.length和size是不一致的。實際上elementData.length表示當前ArrayList的最大容量,而size則表示了實際存放元素的個數。
- 容器初始化函式:通過容器已有資料構造ArrayList。
2 增加元素
/**
* 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);
modCount++;
final int s;
Object[] elementData;
if ((s = size) == (elementData = this.elementData).length)
elementData = grow();
System.arraycopy(elementData, index,
elementData, index + 1,
s - index);
elementData[index] = element;
size = s + 1;
}
add函式過載的包括多個,這裡只列出一個具有代表性的進行說明,其他的add方法可由它推演而來。這個函式做了這麼幾件事,首先檢查要插入的下標是否越界,是的話直接拋異常退出。然後檢查elementData.length和size是否一致,一致說明容量已滿,需要擴容,增加一個元素的容量。將index之後的元素分別拷貝到原下標+1的位置,將index位置設為指定element,並將ArrayList的實際長度加一。
這一步驟的關鍵,或者說ArrayList的關鍵,在於擴容,來看一下擴容的實現。
/**
* 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
* @throws OutOfMemoryError if minCapacity is less than zero
*/
private Object[] grow(int minCapacity) {
return elementData = Arrays.copyOf(elementData,
newCapacity(minCapacity));
}
private Object[] grow() {
return grow(size + 1);
}
/**
* Returns a capacity at least as large as the given minimum capacity.
* Returns the current capacity increased by 50% if that suffices.
* Will not return a capacity greater than MAX_ARRAY_SIZE unless
* the given minimum capacity is greater than MAX_ARRAY_SIZE.
*
* @param minCapacity the desired minimum capacity
* @throws OutOfMemoryError if minCapacity is less than zero
*/
private int newCapacity(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;
int newCapacity = oldCapacity + (oldCapacity >> 1);
if (newCapacity - minCapacity <= 0) {
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA)
return Math.max(DEFAULT_CAPACITY, minCapacity);
if (minCapacity < 0) // overflow
throw new OutOfMemoryError();
return minCapacity;
}
return (newCapacity - MAX_ARRAY_SIZE <= 0)
? newCapacity
: hugeCapacity(minCapacity);
}
當ArrayList容量不夠時,預設需要增加一個元素的長度。在實際執行過程中,是擴容到之前容量的1.5倍,然後判斷是否超過最大限制,超過則報記憶體溢位錯誤。在擴容過程中,最大不得超過MAX_ARRAY_SIZE,即ArrayList的最大長度。
由此可見,向ArrayList插入元素時,當元素個數小於實際容量大小時,只要進行部分陣列的拷貝工作,容量已滿時,需要擴容則要將ArrayList的所有元素拷貝到新建陣列中,這個步驟是比較耗時的。元素的插入確實不是ArrayList的強項。
3 查詢,修改元素
查詢和修改實際是通過下標來訪問和修改陣列元素,時間複雜度只有O(1),相對於LinkedList和其他容器,都具有絕對的速度優勢。
/**
* Returns the element at the specified position in this list.
*
* @param index index of the element to return
* @return the element at the specified position in this list
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
public E get(int index) {
Objects.checkIndex(index, size);
return elementData(index);
}
/**
* Replaces the element at the specified position in this list with
* the specified element.
*
* @param index index of the element to replace
* @param element element to be stored at the specified position
* @return the element previously at the specified position
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
public E set(int index, E element) {
Objects.checkIndex(index, size);
E oldValue = elementData(index);
elementData[index] = element;
return oldValue;
}
只是進行下標檢測,獲取或者替換指定index位置的元素。
4 刪除元素,銷燬
刪除元素對ArrayList來說也有一定的工作量,需要將指定index位置以後的元素統統向前移位,如果ArrayList較長且刪除元素的位置靠前,這就是一個比較耗時的操作了。
/**
* Removes the element at the specified position in this list.
* Shifts any subsequent elements to the left (subtracts one from their
* indices).
*
* @param index the index of the element to be removed
* @return the element that was removed from the list
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
public E remove(int index) {
Objects.checkIndex(index, size);
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;
}
這裡還需要注意,實際上,刪除元素時,並沒有新建一個數組將原陣列拷貝進去,而拷貝元素後將原先末尾的位置置為null並且減小size。這裡再提出一個問題,將陣列元素的最後一位設為null後,虛擬機器會對該位置進行垃圾回收嗎,陣列的實際長度變化了嗎?
最後看ArrayList的銷燬。
/**
* Removes all of the elements from this list. The list will
* be empty after this call returns.
*/
public void clear() {
modCount++;
final Object[] es = elementData;
for (int to = size, i = size = 0; i < to; i++)
es[i] = null;
}
銷燬比較簡單,只是把陣列各元素置為null,並且將size設為0。
小結
容器最重要的功能是儲存和獲取元素,本文從原始碼角度介紹了ArrayList的增刪改查和原理,ArrayList還有一些其他未提到的特性,將在後面的文章中展示。