1. ArrayList概述:
ArrayList是List接口的可變數組的實現。實現了所有可選列表操作,並允許包括 null 在內的所有元素。除了實現 List 接口外,此類還提供一些方法來操作內部用來存儲列表的數組的大小。
每個ArrayList實例都有一個容量,該容量是指用來存儲列表元素的數組的大小。它總是至少等於列表的大小。隨着向ArrayList中不斷添加元 素,其容量也自動增長。自動增長會帶來數據向新數組的重新拷貝,因此,如果可預知數據量的多少,可在構造ArrayList時指定其容量。在添加大量元素 前,應用程序也可以使用ensureCapacity操作來增加ArrayList實例的容量,這可以減少遞增式再分配的數量。
注意,此實現不是同步的。如果多個線程同時訪問一個ArrayList實例,而其中至少一個線程從結構上修改了列表,那麼它必須保持外部同步。
2. ArrayList的實現:
對於ArrayList而言,它實現List接口、底層使用數組保存所有元素。其操作基本上是對數組的操作。下面我們來分析ArrayList的源代碼:
1) 底層使用數組實現:
Java代碼
1. private transient Object[] elementData;
2) 構造方法:
ArrayList提供了三種方式的構造器,可以構造一個默認初始容量爲10的空列表、構造一個指定初始容量的空列表以及構造一個包含指定collection的元素的列表,這些元素按照該collection的迭代器返回它們的順序排列的。
Java代碼
1. public ArrayList() {
2. this( 10 );
3. }
4.
5. public ArrayList( int initialCapacity) {
6. super();
7. if (initialCapacity < 0 )
8. throw new IllegalArgumentException("Illegal Capacity: " + initialCapacity);
9. this.elementData = new Object[initialCapacity];
10. }
11.
12. public ArrayList(Collection<? extends E> c) {
13. elementData = c.toArray();
14. size = elementData.length;
15. // c.toArray might (incorrectly) not return Object[] (see 6260652)
16. if (elementData.getClass() != Object[]. class )
17. elementData = Arrays.copyOf(elementData, size, Object[].class);
18. }
3) 存儲:
ArrayList提供了set(intindex, E element)、add(E e)、add(intindex, E element)、addAll(Collection<? extends E>c)、addAll(int index, Collection<? extends E> c)這些添加元素的方法。下面我們一一講解:
Java代碼
1. // 用指定的元素替代此列表中指定位置上的元素,並返回以前位於該位置上的元素。
2. public E set( int index, E element) {
3. RangeCheck(index);
4.
5. E oldValue = (E) elementData[index];
6. elementData[index] = element;
7. return oldValue;
8. }
Java代碼
1. // 將指定的元素添加到此列表的尾部。
2. public boolean add(E e) {
3. ensureCapacity(size + 1);
4. elementData[size++] = e;
5. return true ;
6. }
Java代碼
1. // 將指定的元素插入此列表中的指定位置。
2. // 如果當前位置有元素,則向右移動當前位於該位置的元素以及所有後續元素(將其索引加1)。
3. public void add( int index, E element) {
4. if (index > size || index < 0)
5. throw new IndexOutOfBoundsException( "Index: " +index+", Size: " +size);
6. // 如果數組長度不足,將進行擴容。
7. ensureCapacity(size+1); // Increments modCount!!
8. // 將 elementData中從Index位置開始、長度爲size-index的元素,
9. // 拷貝到從下標爲index+1位置開始的新的elementData數組中。
10. // 即將當前位於該位置的元素以及所有後續元素右移一個位置。
11. System.arraycopy(elementData, index, elementData, index + 1, size - index);
12. elementData[index] = element;
13. size++;
14. }
Java代碼
1. // 按照指定collection的迭代器所返回的元素順序,將該collection中的所有元素添加到此列表的尾部。
2. public boolean addAll(Collection<? extends E> c) {
3. Object[] a = c.toArray();
4. int numNew = a.length;
5. ensureCapacity(size + numNew); // Increments modCount
6. System.arraycopy(a, 0, elementData, size, numNew);
7. size += numNew;
8. return numNew != 0 ;
9. }
Java代碼
1. // 從指定的位置開始,將指定collection中的所有元素插入到此列表中。
2. public boolean addAll( int index, Collection<? extends E> c) {
3. if (index > size || index < 0)
4. throw new IndexOutOfBoundsException(
5. "Index: " + index + ", Size: " + size);
6.
7. Object[] a = c.toArray();
8. int numNew = a.length;
9. ensureCapacity(size + numNew); // Increments modCount
10.
11. int numMoved = size - index;
12. if (numMoved > 0 )
13. System.arraycopy(elementData, index, elementData, index + numNew, numMoved);
14.
15. System.arraycopy(a, 0, elementData, index, numNew);
16. size += numNew;
17. return numNew != 0 ;
18. }
4) 讀取:
Java代碼
1. // 返回此列表中指定位置上的元素。
2. public E get( int index) {
3. RangeCheck(index);
4.
5. return (E) elementData[index];
6. }
5) 刪除:
ArrayList提供了根據下標或者指定對象兩種方式的刪除功能。如下:
Java代碼
1. // 移除此列表中指定位置上的元素。
2. public E remove( int index) {
3. RangeCheck(index);
4.
5. modCount++;
6. E oldValue = (E) elementData[index];
7.
8. int numMoved = size - index - 1 ;
9. if (numMoved > 0 )
10. System.arraycopy(elementData, index+1, elementData, index, numMoved);
11. elementData[--size] = null; // Let gc do its work
12.
13. return oldValue;
14. }
Java代碼
1. // 移除此列表中首次出現的指定元素(如果存在)。這是應爲ArrayList中允許存放重複的元素。
2. public boolean remove(Object o) {
3. // 由於ArrayList中允許存放null,因此下面通過兩種情況來分別處理。
4. if (o == null ) {
5. for ( int index = 0; index < size; index++)
6. if (elementData[index] == null ) {
7. // 類似remove(int index),移除列表中指定位置上的元素。
8. fastRemove(index);
9. return true ;
10. }
11. } else {
12. for ( int index = 0; index < size; index++)
13. if (o.equals(elementData[index])) {
14. fastRemove(index);
15. return true ;
16. }
17. }
18. return false ;
19. }
注意:從數組中移除元素的操作,也會導致被移除的元素以後的所有元素的向左移動一個位置。
6) 調整數組容量:
從上面介紹的向ArrayList中存儲元素的代碼中,我們看到,每當向數組中添加元素時,都要去檢查添加後元素的個數是否會超出當前數組的長度,如果超出,數組將會進行擴容,以滿足添加數據的需求。數組擴容通過一個公開的方法ensureCapacity(intminCapacity)來實現。在實際添加大量元素前,我也可以使用ensureCapacity來手動增加ArrayList實例的容量,以減少遞增 式再分配的數量。
Java代碼
1. public void ensureCapacity( int minCapacity) {
2. modCount++;
3. int oldCapacity = elementData.length;
4. if (minCapacity > oldCapacity) {
5. Object oldData[] = elementData;
6. int newCapacity = (oldCapacity * 3 )/ 2 + 1;
7. if (newCapacity < minCapacity)
8. newCapacity = minCapacity;
9. // minCapacity is usually close to size, so this is a win:
10. elementData = Arrays.copyOf(elementData, newCapacity);
11. }
12. }
從上述代碼中可以看出,數組進行擴容時,會將老數組中的元素重新拷貝一份到新的數組中,每次數組容量的增長大約是其原容量的1.5倍。這種操作的代價是很高的,因此在實際使用時,我們應該儘量避免數組容量的擴張。當我們可預知要保存的元素的多少時,要在構造ArrayList實例時,就指定其容量,以避免數組擴容的發生。或者根據實際需求,通過調用ensureCapacity方法來手動增加ArrayList實例的容量。
ArrayList還給我們提供了將底層數組的容量調整爲當前列表保存的實際元素的大小的功能。它可以通過trimToSize方法來實現。代碼如下:
Java代碼
1. public void trimToSize() {
2. modCount++;
3. int oldCapacity = elementData.length;
4. if (size < oldCapacity) {
5. elementData = Arrays.copyOf(elementData, size);
6. }
7. }
7) Fail-Fast機制:
ArrayList也採用了快速失敗的機制,通過記錄modCount參數來實現。在面對併發的修改時,迭代器很快就會完全失敗,而不是冒着在將來某個不確定時間發生任意不確定行爲的風險。具體介紹請參考我之前的文章深入Java集合學習系列:HashMap的實現原理 中的Fail-Fast機制。
8) 關於其他的一些方法的實現都很簡單易懂,讀者可參照API文檔和源代碼,一看便知,這裏就不再多說。