Java 2源碼解讀:java.util.ArrayList

來源:互聯網
上載者:User
相關源碼下載:
java.util.ArrayList
java.util.AbstractList
java.util.List

ArrayList是List介面的一個可變長數組實現。實現了所有List介面的操作,並允許儲存null值。除了沒有進行同步,ArrayList基本等同於Vector。在Vector中幾乎對所有的方法都進行了同步,但ArrayList僅對writeObject和readObject進行了同步,其它比如add(Object)、remove(int)等都沒有同步。

1.儲存

ArrayList使用一個Object的數組儲存元素。
private transient Object elementData[];
ArrayList實現了java.io.Serializable介面,這兒的transient標示這個屬性不需要自動序列化。下面會在writeObject()方法中詳細講解為什麼要這樣作。

2.add和remove

  1.     public boolean add(Object o) {
  2.     ensureCapacity(size + 1);  // Increments modCount!!
  3.     elementData[size++] = o;
  4.     return true;
  5.     }

注意這兒的ensureCapacity()方法,它的作用是保證elementData數組的長度可以容納一個新元素。在“自動變長機制”中將詳細講解。

  1.     public Object remove(int index) {
  2.     RangeCheck(index);
  3.     modCount++;
  4.     Object oldValue = elementData[index];
  5.     int numMoved = size - index - 1;
  6.     if (numMoved > 0)
  7.         System.arraycopy(elementData, index+1, elementData, index,
  8.                  numMoved);
  9.     elementData[--size] = null// Let gc do its work
  10.     return oldValue;
  11.     }

RangeCheck()的作用是進行邊界檢查。由於ArrayList採用一個對象數組儲存元素,所以在刪除一個元素時需要把後面的元素前移。刪除一個元素時只是把該元素在elementData數組中的引用置為null,具體的對象的銷毀由垃圾收集器負責。
modCount的作用將在下面的“iterator()中的同步”中說明。
註:在前移時使用了System提供的一個實用方法:arraycopy(),在本例中可以看出System.arraycopy()方法可以對同一個數組進行操作,這個方法是一個native方法,如果對同一個數組進行操作時,會首先把從源部分拷貝到一個臨時數組,在把臨時數組的元素拷貝到目標位置。

3.自動變長機制

在執行個體化一個ArrayList時,你可以指定一個初始容量。這個容量就是elementData數組的初始長度。如果你使用:

  1.     ArrayList list = new ArrayList();

則使用預設的容量:10。

  1.     public ArrayList() {
  2.     this(10);
  3.     }

ArrayList提供了四種add()方法,

  • public boolean add(Object o)
  • public void add(int index, Object element)
  • public boolean addAll(Collection c)
  • public boolean addAll(int index, Collection c)

在每一種add()方法中,都首先調用了一個ensureCapacity(int miniCapacity)方法,這個方法保證elementData數組的長度不小於miniCapacity。ArrayList的自動變長機制就是在這個方法中實現的。

  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.         elementData = new Object[newCapacity];
  10.         System.arraycopy(oldData, 0, elementData, 0, size);
  11.     }
  12.     }

從這個方法實現中可以看出ArrayList每次擴容,都擴大到原來大小的1.5倍。
每種add()方法的實現都大同小異,下面給出add(Object)方法的實現:

  1.     public boolean add(Object o) {
  2.     ensureCapacity(size + 1);  // Increments modCount!!
  3.     elementData[size++] = o;
  4.     return true;
  5.     }

4.iterator()中的同步

在父類AbstractList中定義了一個int型的屬性:modCount,記錄了ArrayList結構性變化的次數。

  1.     protected transient int modCount = 0;

在ArrayList的所有涉及結構變化的方法中都增加modCount的值,包括:add()、remove()、addAll()、removeRange()及clear()方法。這些方法每調用一次,modCount的值就加1。
註:add()及addAll()方法的modCount的值是在其中調用的ensureCapacity()方法中增加的。

AbstractList中的iterator()方法(ArrayList直接繼承了這個方法)使用了一個私人內部成員類Itr,產生一個Itr對象(Iterator介面)返回:

  1.     public Iterator iterator() {
  2.     return new Itr();
  3.     }

Itr實現了Iterator()介面,其中也定義了一個int型的屬性:expectedModCount,這個屬性在Itr類初始化時被賦予ArrayList對象的modCount屬性的值。

  1.     int expectedModCount = modCount;

註:內部成員類Itr也是ArrayList類的一個成員,它可以訪問所有的AbstractList的屬性和方法。理解了這一點,Itr類的實現就容易理解了。

在Itr.hasNext()方法中:

  1.     public boolean hasNext() {
  2.         return cursor != size();
  3.     }

調用了AbstractList的size()方法,比較當前游標位置是否越界。

在Itr.next()方法中,Itr也調用了定義在AbstractList中的get(int)方法,返回當前游標處的元素:

  1.     public Object next() {
  2.         try {
  3.         Object next = get(cursor);
  4.         checkForComodification();
  5.         lastRet = cursor++;
  6.         return next;
  7.         } catch(IndexOutOfBoundsException e) {
  8.         checkForComodification();
  9.         throw new NoSuchElementException();
  10.         }
  11.     }

注意,在next()方法中調用了checkForComodification()方法,進行對修改的同步檢查:

  1.     final void checkForComodification() {
  2.         if (modCount != expectedModCount)
  3.         throw new ConcurrentModificationException();
  4.     }

現在對modCount和expectedModCount的作用應該非常清楚了。在對一個集合對象進行跌代操作的同時,並不限制對集合對象的元素進行操作,這些操作包括一些可能引起跌代錯誤的add()或remove()等危險操作。在AbstractList中,使用了一個簡單的機制來規避這些風險。這就是modCount和expectedModCount的作用所在。

5.序列化支援

ArrayList實現了java.io.Serializable介面,所以ArrayList對象可以序列化到持久儲存介質中。ArrayList的主要屬性定義如下:

  • private static final long serialVersionUID = 8683452581122892189L;
  • private transient Object elementData[];
  • private int size;

可以看出serialVersionUID和size都將自動序列化到介質中,但elementData數組對象卻定義為transient了。也就是說ArrayList中的所有這些元素都不會自動系列化到介質中。為什麼要這樣實現?因為elementData數組中儲存的“元素”其實僅是對這些元素的一個引用,並不是真正的對象,序列化一個對象的引用是毫無意義的,因為序列化是為了還原序列化,當你還原序列化時,這些對象的引用已經不可能指向原來的對象了。所以在這兒需要手工的對ArrayList的元素進行序列化操作。這就是writeObject()的作用。

  1.     private synchronized void writeObject(java.io.ObjectOutputStream s)
  2.         throws java.io.IOException{
  3.     // Write out element count, and any hidden stuff
  4.     s.defaultWriteObject();
  5.    // Write out array length
  6.     s.writeInt(elementData.length);
  7.     // Write out all elements in the proper order.
  8.     for (int i=0; i<size; i++)
  9.             s.writeObject(elementData[i]);
  10.     }

這樣元素數組elementData中的所以元素對象就可以正確地序列化到儲存介質了。
對應的readObject()也按照writeObject()方法的順序從輸入資料流中讀取:

  1.     private synchronized void readObject(java.io.ObjectInputStream s)
  2.         throws java.io.IOExceptionClassNotFoundException {
  3.     // Read in size, and any hidden stuff
  4.     s.defaultReadObject();
  5.     // Read in array length and allocate array
  6.     int arrayLength = s.readInt();
  7.     elementData = new Object[arrayLength];
  8.     // Read in all elements in the proper order.
  9.     for (int i=0; i<size; i++)
  10.             elementData[i] = s.readObject();
  11.     }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.