1. ArrayList概述:
ArrayList是List接口的可變數(shù)組的實(shí)現(xiàn)。實(shí)現(xiàn)了所有可選列表操作,并允許包括 null 在內(nèi)的所有元素。除了實(shí)現(xiàn) List 接口外,此類還提供一些方法來操作內(nèi)部用來存儲(chǔ)列表的數(shù)組的大小。
每個(gè)ArrayList實(shí)例都有一個(gè)容量,該容量是指用來存儲(chǔ)列表元素的數(shù)組的大小。它總是至少等于列表的大小。隨著向ArrayList中不斷添加元 素,其容量也自動(dòng)增長。自動(dòng)增長會(huì)帶來數(shù)據(jù)向新數(shù)組的重新拷貝,因此,如果可預(yù)知數(shù)據(jù)量的多少,可在構(gòu)造ArrayList時(shí)指定其容量。在添加大量元素 前,應(yīng)用程序也可以使用ensureCapacity操作來增加ArrayList實(shí)例的容量,這可以減少遞增式再分配的數(shù)量。
注意,此實(shí)現(xiàn)不是同步的。如果多個(gè)線程同時(shí)訪問一個(gè)ArrayList實(shí)例,而其中至少一個(gè)線程從結(jié)構(gòu)上修改了列表,那么它必須保持外部同步。
2. ArrayList的實(shí)現(xiàn):
對(duì)于ArrayList而言,它實(shí)現(xiàn)List接口、底層使用數(shù)組保存所有元素。其操作基本上是對(duì)數(shù)組的操作。下面我們來分析ArrayList的源代碼:
1) 底層使用數(shù)組實(shí)現(xiàn):
- private transient Object[] elementData;
2) 構(gòu)造方法:
ArrayList提供了三種方式的構(gòu)造器,可以構(gòu)造一個(gè)默認(rèn)初始容量為10的空列表、構(gòu)造一個(gè)指定初始容量的空列表以及構(gòu)造一個(gè)包含指定collection的元素的列表,這些元素按照該collection的迭代器返回它們的順序排列的。
- public ArrayList() {
- this(10);
- }
-
- public ArrayList(int initialCapacity) {
- super();
- if (initialCapacity < 0)
- throw new IllegalArgumentException("Illegal Capacity: "+ initialCapacity);
- this.elementData = new Object[initialCapacity];
- }
-
- public ArrayList(Collection<? extends E> c) {
- elementData = c.toArray();
- size = elementData.length;
-
- if (elementData.getClass() != Object[].class)
- elementData = Arrays.copyOf(elementData, size, Object[].class);
- }
3) 存儲(chǔ):
ArrayList提供了set(int index, E element)、add(E e)、add(int index, E element)、addAll(Collection<? extends E> c)、addAll(int index, Collection<? extends E> c)這些添加元素的方法。下面我們一一講解:
-
- public E set(int index, E element) {
- RangeCheck(index);
-
- E oldValue = (E) elementData[index];
- elementData[index] = element;
- return oldValue;
- }
-
- public boolean add(E e) {
- ensureCapacity(size + 1);
- elementData[size++] = e;
- return true;
- }
-
-
- public void add(int index, E element) {
- if (index > size || index < 0)
- throw new IndexOutOfBoundsException("Index: "+index+", Size: "+size);
-
- ensureCapacity(size+1);
-
-
-
- System.arraycopy(elementData, index, elementData, index + 1, size - index);
- elementData[index] = element;
- size++;
- }
-
- public boolean addAll(Collection<? extends E> c) {
- Object[] a = c.toArray();
- int numNew = a.length;
- ensureCapacity(size + numNew);
- System.arraycopy(a, 0, elementData, size, numNew);
- size += numNew;
- return numNew != 0;
- }
-
- public boolean addAll(int index, Collection<? extends E> c) {
- if (index > size || index < 0)
- throw new IndexOutOfBoundsException(
- "Index: " + index + ", Size: " + size);
-
- Object[] a = c.toArray();
- int numNew = a.length;
- ensureCapacity(size + numNew);
-
- int numMoved = size - index;
- if (numMoved > 0)
- System.arraycopy(elementData, index, elementData, index + numNew, numMoved);
-
- System.arraycopy(a, 0, elementData, index, numNew);
- size += numNew;
- return numNew != 0;
- }
4) 讀取:
-
- public E get(int index) {
- RangeCheck(index);
-
- return (E) elementData[index];
- }
5) 刪除:
ArrayList提供了根據(jù)下標(biāo)或者指定對(duì)象兩種方式的刪除功能。如下:
-
- public E remove(int index) {
- RangeCheck(index);
-
- modCount++;
- E oldValue = (E) elementData[index];
-
- int numMoved = size - index - 1;
- if (numMoved > 0)
- System.arraycopy(elementData, index+1, elementData, index, numMoved);
- elementData[--size] = null;
-
- return oldValue;
- }
-
- public boolean remove(Object o) {
-
- if (o == null) {
- for (int index = 0; index < size; index++)
- if (elementData[index] == null) {
-
- fastRemove(index);
- return true;
- }
- } else {
- for (int index = 0; index < size; index++)
- if (o.equals(elementData[index])) {
- fastRemove(index);
- return true;
- }
- }
- return false;
- }
注意:從數(shù)組中移除元素的操作,也會(huì)導(dǎo)致被移除的元素以后的所有元素的向左移動(dòng)一個(gè)位置。
6) 調(diào)整數(shù)組容量:
從上面介紹的向ArrayList中存儲(chǔ)元素的代碼中,我們看到,每當(dāng)向數(shù)組中添加元素時(shí),都要去檢查添加后元素的個(gè)數(shù)是否會(huì)超出當(dāng)前數(shù)組的長度,如果超 出,數(shù)組將會(huì)進(jìn)行擴(kuò)容,以滿足添加數(shù)據(jù)的需求。數(shù)組擴(kuò)容通過一個(gè)公開的方法ensureCapacity(int minCapacity)來實(shí)現(xiàn)。在實(shí)際添加大量元素前,我也可以使用ensureCapacity來手動(dòng)增加ArrayList實(shí)例的容量,以減少遞增 式再分配的數(shù)量。
- public void ensureCapacity(int minCapacity) {
- modCount++;
- int oldCapacity = elementData.length;
- if (minCapacity > oldCapacity) {
- Object oldData[] = elementData;
- int newCapacity = (oldCapacity * 3)/2 + 1;
- if (newCapacity < minCapacity)
- newCapacity = minCapacity;
-
- elementData = Arrays.copyOf(elementData, newCapacity);
- }
- }
從上述代碼中可以看出,數(shù)組進(jìn)行擴(kuò)容時(shí),會(huì)將老數(shù)組中的元素重新拷貝一份到新的數(shù)組中,每次數(shù)組容量的增長大約是其原容量的1.5倍。這種操作的代價(jià)是很 高的,因此在實(shí)際使用時(shí),我們應(yīng)該盡量避免數(shù)組容量的擴(kuò)張。當(dāng)我們可預(yù)知要保存的元素的多少時(shí),要在構(gòu)造ArrayList實(shí)例時(shí),就指定其容量,以避免 數(shù)組擴(kuò)容的發(fā)生。或者根據(jù)實(shí)際需求,通過調(diào)用ensureCapacity方法來手動(dòng)增加ArrayList實(shí)例的容量。
ArrayList還給我們提供了將底層數(shù)組的容量調(diào)整為當(dāng)前列表保存的實(shí)際元素的大小的功能。它可以通過trimToSize方法來實(shí)現(xiàn)。代碼如下:
- public void trimToSize() {
- modCount++;
- int oldCapacity = elementData.length;
- if (size < oldCapacity) {
- elementData = Arrays.copyOf(elementData, size);
- }
- }
7) Fail-Fast機(jī)制:
ArrayList也采用了快速失敗的機(jī)制,通過記錄modCount參數(shù)來實(shí)現(xiàn)。在面對(duì)并發(fā)的修改時(shí),迭代器很快就會(huì)完全失敗,而不是冒著在將來某個(gè)不確定時(shí)間發(fā)生任意不確定行為的風(fēng)險(xiǎn)。具體介紹請(qǐng)參考我之前的文章深入Java集合學(xué)習(xí)系列:HashMap的實(shí)現(xiàn)原理 中的Fail-Fast機(jī)制。
8) 關(guān)于其他 的一些方法的實(shí)現(xiàn)都很簡單易懂,讀者可參照API文檔和源代碼,一看便知,這里就不再多說。
3. 相關(guān)閱讀:
本系列的文章之前還整理了以下幾篇,有興趣的可以參考,望與大家分享心得,共同進(jìn)步:
1) 深入Java集合學(xué)習(xí)系列:HashMap的實(shí)現(xiàn)原理 。
2) 深入Java集合學(xué)習(xí)系列:LinkedHashMap的實(shí)現(xiàn)原理 。
3) 深入Java集合學(xué)習(xí)系列:HashSet的實(shí)現(xiàn)原理 。
4) 深入Java集合學(xué)習(xí)系列:LinkedHashSet的實(shí)現(xiàn)原理 。