2017/02/16 看完CopyOnWriteArrayList後對ArrayList中的一些代碼重新做了注釋。發現了一些第一次看沒注意到的細節。希望各位看後有所收穫。 —————
看原始碼是一個程式員必備技能。
這裡就做先寫一個ArrayList原始碼的解讀。所有的解讀都寫在原始碼注釋上,簡單與類似的不再重複寫注釋。
解讀的JDK版本為1.7。
希望各位看下來能有收穫。
2017/06/03更新:
重點知識集合:
預設初始化容量為10;
底層實現其實就是數組,沒有Object Storage Service的時候,其實就是空數組
迭代器中add()、remove()會報異常是因為調用add()等方法時會改變modCount,而迭代的時候會判斷期望的modCount和實際的modCount是否保持一致,不一致則拋出異常。
最大集合大小為Integer.MAX_VALUE-8,因為一些虛擬機器儲存了一些頭欄位在數組中,這時去分配最大容量為Integer.MAX_VALUE
就可能導致OutOfMemoryError錯誤,即請求的數組大小超過虛擬機器限制。
預設每次擴容原來容量的0.5倍。如果指定的容量比預設擴容還要大,那麼就按指定容量來擴容
ArrayList原始碼:
package java.util;public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable{ private static final long serialVersionUID = 8683452581122892189L; /** * Default initial capacity. *預設初始化容量 */ private static final int DEFAULT_CAPACITY = 10; /** * 空數組執行個體(當ArrayList中沒有資料時,返回的就是這個) * Shared empty array instance used for empty instances. */ private static final Object[] EMPTY_ELEMENTDATA = {}; /** * ArrayList中被儲存的對象,但沒有對象被儲存時,elementData == EMPTY_ELEMENTDATA * 如果加入了對象,那麼此時容量將擴大到DEFAULT_CAPACITY。 *另外,當序列化的時候,被transient修飾的變數是不會被序列化的,這就是序列化的作用 *這裡使用transient的原因: *因為ArrayList實際上是動態數組,每次在放滿以後自動成長設定的長度值,如果數組自動成長長度設為100, *而實際只放了一個元素,那就會序列化很多null元素,所以ArrayList把elementData設定為transient。 *而ArrayList為了達到序列化與還原序列化,自己重寫了writeObject與readObject。 * 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 == EMPTY_ELEMENTDATA will be expanded to * DEFAULT_CAPACITY when the first element is added. */ private transient Object[] elementData; /** * The size of the ArrayList (the number of elements it contains). * * @serial */ private int size; /** * 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) { super(); if (initialCapacity < 0) throw new IllegalArgumentException("Illegal Capacity: "+ initialCapacity); this.elementData = new Object[initialCapacity]; } /** *構造一個空的ArrayList執行個體,但是此時空執行個體中是沒有容量的 * Constructs an empty list with an initial capacity of ten. */ public ArrayList() { super(); this.elementData = EMPTY_ELEMENTDATA; } /** * 如果c是通過Arrays.asList()方法轉換來的集合,比如以下代碼:List<String> list = Arrays.asList("abc"); *那麼輸出list.getClass()可見為:class java.util.Arrays$ArrayList *如果再將list.toArray()給Object [] objectArray,輸出objectArray.class:class [Ljava.lang.String; *所以,此時objectArray[0] = new Object();會報儲存異常.因此,如果發現elementData.getClass與Object[].class不一樣,則需要建立一個Object[]。 *注意,如果將List<String> list = Arrays.asList("abc");改為List<String> list = Lists.newArrayList()就不會有問題 *另外,see 6260652中6260652指的是JDK的bug編號。可以去官網查看bug詳情 *程式碼範例如下: /** *正常 */ List<String> list = new ArrayList<String>(); list.add("asd"); Object[] objects = list.toArray(); objects[0] = new Object(); /** * 出錯 */ List<String> listError = Arrays.asList("abc"); Object[] objects1 = listError.toArray(); objects1[0] = new Object(); * 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(); size = elementData.length; // c.toArray might (incorrectly) not return Object[] (see 6260652) if (elementData.getClass() != Object[].class) elementData = Arrays.copyOf(elementData, size, Object[].class); } /** *size是ArrayList中實際儲存的大小,而elementData是數組,其length是建立時候可以被賦予的 *capacity,該方法目的是將此 ArrayList 執行個體的容量調整為列表的當前儲存大小。 *而modCount是ArrayList繼承自AbstractList的protected欄位,表示:已從結構上修改此List的次數。 *迭代器中的快速失敗就是由modCount來提供的,具體為:如果子類希望提供快速失敗迭代器(和列表迭代器),則它只需在其 add(int, E) 和 remove(int) *方法(以及它所重寫的、導致列表結構上修改的任何其他方法)中增加此欄位。add(int, E) 或 remove(int) *的單個調用中此欄位添加的數量不得超過1,否則迭代器(和列表迭代器)將拋出虛假的 *ConcurrentModificationExceptions。如果某個實現不希望提供快速失敗迭代器,則可以忽略此欄位。 * * Trims the capacity of this <tt>ArrayList</tt> instance to be the * list's current size. An application can use this operation to minimize * the storage of an <tt>ArrayList</tt> instance. */ public void trimToSize() { modCount++; if (size < elementData.length) { elementData = Arrays.copyOf(elementData, size); } } /** *修改ArrayList的容量,使其容量為minCapacity *如果是空表,那麼調用ensureCapacity可以隨意設定比0大的容量。 *如果不是空表,比如是通過ArrayList(int initCapacity)來初始化容量的,那麼調用 *ensureCapacity時,如果minCapacity還比預設的容量小,那麼就不重新設定 *(注意:個人感覺可以把其中的DEFAULT_CAPACITY變成Math.max(this.size(),DEFAULT_CAPACITY)) * 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. * * @param minCapacity the desired minimum capacity */ public void ensureCapacity(int minCapacity) { int minExpand = (elementData != EMPTY_ELEMENTDATA) // any size if real element table ? 0 // larger than default for 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 == EMPTY_ELEMENTDATA) { minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity); } ensureExplicitCapacity(minCapacity); } /** *elementData為數組,已經確定了大小,如果收縮的話,可能會溢出,所以只能擴容 */ private void ensureExplicitCapacity(int minCapacity) { modCount++; // overflow-conscious code if (minCapacity - elementData.length > 0) grow(minCapacity); } /** *最大集合大小,使用Integer.MAX_VALUE-8的意義在於: *一些虛擬機器儲存了一些頭欄位在數組中,這時去分配最大容量為Integer.MAX_VALUE *就可能導致OutOfMemoryError錯誤,即請求的數組大小超過虛擬機器限制。 * The maximum size of array to allocate. * Some VMs reserve some header words in an array. * Attempts to allocate larger arrays may result in * OutOfMemoryError: Requested array size exceeds VM limit */ private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8; /** *預設每次擴容原來容量的0.5倍。如果指定的容量比預設擴容還要大,那麼就按指定容量來擴容 *如果要擴容的容量比最大容量還要大,那麼調用hugeCapacity()使用指定容量與最大容量比較, *如果指定容量也比最大容量大,那麼就返回Integer.MAX_VALUE進行擴容。 * 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); } private static int hugeCapacity(int minCapacity) { if (minCapacity < 0) // overflow throw new OutOfMemoryError(); return (minCapacity > MAX_ARRAY_SIZE) ? Integer.MAX_VALUE : MAX_ARRAY_SIZE; } /** * Returns the number of elements in this list. * * @return the number of elements in this list */ public int size() { return size; } /** * Returns <tt>true</tt> if this list contains no elements. * * @return <tt>true</tt> if this list contains no elements */ public boolean isEmpty() { return size == 0; } /** * Returns <tt>true</tt> if this list contains the specified element. * More formally, returns <tt>true</tt> if and only if this list contains * at least one element <tt>e</tt> such that * <tt>(o==null ? e==null : o.equals(e))</tt>. * * @param o element whose presence in this list is to be tested * @return <tt>true</tt> if this list contains the specified element */ public boolean contains(Object o) { return indexOf(o) >= 0; } /** * Returns the index of the first occurrence of the specified element * in this list, or -1 if this list does not contain the element. * More formally, returns the lowest index <tt>i</tt> such that * <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>, * or -1 if there is no such index. */ public int indexOf(Object o) { if (o == null) { for (int i = 0; i < size; i++) if (elementData[i]==null) return i; } else { for (int i = 0; i < size; i++) if (o.equals(elementData[i])) return i; } return -1; } /** * Returns the index of the last occurrence of the specified element * in this list, or -1 if this list does not contain the element. * More formally, returns the highest index <tt>i</tt> such that * <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>, * or -1 if there is no such index. */ public int lastIndexOf(Object o) { if (o == null) { for (int i = size-1; i >= 0; i--) if (elementData[i]==null) return i; } else { for (int i = size-1; i >= 0; i--) if (o.equals(elementData[i])) return i; } return -1; } /** *這裡的複製時淺複製,雖然elementData是Arrays.copyOf出來的,即數組是新的, *但數組中的元素引用是舊的。 *代碼測試執行個體:(為方便,直接把屬性定義成public了) StringUtilTest stringUtilTest1 = new StringUtilTest(); StringUtilTest stringUtilTest = new StringUtilTest(); stringUtilTest.age = 999; stringUtilTest1.age = 999; ArrayList<StringUtilTest> stringUtilTestList = new ArrayList<StringUtilTest>(4); stringUtilTestList.add(stringUtilTest); stringUtilTestList.add(stringUtilTest1); ArrayList<StringUtilTest> clone = (ArrayList) stringUtilTestList.clone(); clone.get(0).age = 111; System.out.println("list:"+stringUtilTestList); System.out.println("clone:"+clone); System.out.println(clone.get(1) == stringUtilTestList.get(1)); *輸出結果: list:[StringUtilTest{age=111}, StringUtilTest{age=999}] clone:[StringUtilTest{age=111}, StringUtilTest{age=999}] true * Returns a shallow copy of this <tt>ArrayList</tt> instance. (The * elements themselves are not copied.) * * @return a clone of this <tt>ArrayList</tt> instance */ public Object clone() { try { @SuppressWarnings("unchecked") ArrayList<E> v = (ArrayList<E>) super.clone(); v.elementData = Arrays.copyOf(elementData, size); v.modCount = 0; return v; } catch (CloneNotSupportedException e) { // this shouldn't happen, since we are Cloneable throw new InternalError(); } } /** * Returns an array containing all of the elements in this list * in proper sequence (from first to last element). * * <p>The returned array will be "safe" in that no references to it are * maintained by this list. (In other words, this method must allocate * a new array). The caller is thus free to modify the returned array. * * <p>This method acts as bridge between array-based and collection-based * APIs. * * @return an array containing all of the elements in this list in * proper sequence */ public Object[] toArray() { return Arrays.copyOf(elementData, size); } /** *如果a的長度還沒有size大,那麼顯然elementData中元素不能被全部放入數組內 *此時就不會再使用a.length作為複製容量,而是使用size。 *如果a.length不比size小,那麼就在直接copy到a上面,複製長度為size,因為elementData *的實際大小為size,如果a.length比size還大,顯然a中有多餘空間,那麼在a[size]處設定 *為null,好確定實際大小。(僅在調用者知道列表中不包含任何 null 元素時才能用此方法確定列表長度)。 * Returns an array containing all of the elements in this list in proper * sequence (from first to last element); the runtime type of the returned * array is that of the specified array. If the list fits in the * specified array, it is returned therein. Otherwise, a new array is * allocated with the runtime type of the specified array and the size of * this list. * * <p>If the list fits in the specified array with room to spare * (i.e., the array has more elements than the list), the element in * the array immediately following the end of the collection is set to * <tt>null</tt>. (This is useful in determining the length of the * list <i>only</i> if the caller knows that the list does not contain * any null elements.) * * @param a the array into which the elements of the list are to * be stored, if it is big enough; otherwise, a new array of the * same runtime type is allocated for this purpose. * @return an array containing the elements of the list * @throws ArrayStoreException if the runtime type of the specified array * is not a supertype of the runtime type of every element in * this list * @throws NullPointerException if the specified array is null */ @SuppressWarnings("unchecked") public <T> T[] toArray(T[] a) { if (a.length < size) // Make a new array of a's runtime type, but my contents: return (T[]) Arrays.copyOf(elementData, size, a.getClass()); System.arraycopy(elementData, 0, a, 0, size); if (a.length > size) a[size] = null; return a; } // Positional Access Operations @SuppressWarnings("unchecked") E elementData(int index) { return (E) elementData[index]; } /** *在擷取之前會進行範圍檢查,看是否下標越界 * 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) { rangeCheck(index); return elementData(index); } /** *替代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) { rangeCheck(index); E oldValue = elementData(index); elementData[index] = element; return oldValue; } /** *擴容的時候有modCount * Appends the specified element to the end of this list. * * @param e element to be appended to this list * @return <tt>true</tt> (as specified by {@link Collection#add}) */ public boolean add(E e) { ensureCapacityInternal(size + 1); // Increments modCount!! elementData[size++] = e; return true; } /** *在數組複製的時候把elementData[index]及以後的元素都挪一個位置,即 *原來的elementData[index]變成了現在的element[index+1] * 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++; } /** *numMoved就是需要被移動的長度,假設index=0帶入方便理解。 *其中在數組中刪除其實也就是實現覆蓋,然後將最後一個元素置為null, *並返回被刪除的元素 * 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) { 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; } /** *移除此列表中首次出現的指定元素,注意,o要重寫equals方法 * Removes the first occurrence of the specified element from this list, * if it is present. If the list does not contain the element, it is * unchanged. More formally, removes the element with the lowest index * <tt>i</tt> such that * <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt> * (if such an element exists). Returns <tt>true</tt> if this list * contained the specified element (or equivalently, if this list * changed as a result of