JDK原始碼閱讀—ArrayList的實現
1 繼承結構圖
ArrayList繼承AbstractList,實現了List介面
2 建構函式
transient Object[] elementData; // 陣列儲存元素 private int size; // 記錄長度
size記錄ArrayList的長度,elementData記錄元素的值
transient是Java語言的關鍵字,用來表示一個域不是該物件序列化的一部分。當一個物件被序列化的時候,transient型變數的值不包括在序列化的表示中,然而非transient型的變數是被包括進去的。transient詳細介紹如連結:
三種構造方法
public ArrayList(int initialCapacity)
引數為長度,必須為大於等於0整數,如果傳入0,與第二種構造方法結果相同,都是建立一個空的Object陣列
public ArrayList()
建立一個空的Object陣列
public ArrayList(Collection <?extendsE> c)
如果引數不為空,則使用Collection的toArray方法,把c轉為物件陣列,否則建立一個空的Object陣列
3 需要注意的方法
publicE set(int index, E element) { rangeCheck(index); E oldValue = elementData(index); elementData[index] = element; return oldValue; }
常使用的是set(E element)這個方法 set方法如果使用set(int index, E element)這個方法,index對應的位置如果已經有值,該值會被新set的物件替換,並且返回舊值
public voidadd(int index, E element) { rangeCheckForAdd(index); ensureCapacityInternal(size + 1); // Increments modCount!! System.arraycopy(elementData, index, elementData, index + 1, size - index); elementData[index] = element; size++; }
平時使用都是使用add(E element),如果使用了add(int index, E element)這個方法,從上圖的實現來看,它會先把記錄元素的陣列長度加1,然後把index之後的元素全部都後移一位,然後把新插入的元素放在索引為index的位置
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; }
remove(int index)的刪除方法是把index之後的元素都往前移動一個位置,所以如果你用for迴圈遍歷ArrayList並且在迴圈中滿足某個條件就remove掉一個元素,那麼就會丟擲IndexOutOfBoundsException
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; }
Remove(Object o)會從前往後查詢,找到第一個相等的物件進行刪除,刪除的原理也是後面的元素前移一位,所以遍歷ArrayList最好用迭代器進行遍歷。
public boolean addAll(int index, Collection<? extends E> c) { rangeCheckForAdd(index); Object[] a = c.toArray(); int numNew = a.length; ensureCapacityInternal(size + numNew); // Increments modCount 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; }
addAll(int index, Collection c)如果當前ArrayList的長度小於index,直接從index開始,把c的元素按順序擺放,如果當前ArrayList的長度大於Index,則把c插入到當前ArrayList的index 到index+c.length的位置,再把原ArrayList的剩餘元素接到後面
4 不常用方法
private boolean batchRemove(Collection<?> c, boolean complement) { final Object[] elementData = this.elementData; int r = 0, w = 0; boolean modified = false; try { for (; r < size; r++) if (c.contains(elementData[r]) == complement) elementData[w++] = elementData[r]; } finally { // Preserve behavioral compatibility with AbstractCollection, // even if c.contains() throws. if (r != size) { System.arraycopy(elementData, r, elementData, w, size - r); w += size - r; } if (w != size) { // clear to let GC do its work for (int i = w; i < size; i++) elementData[i] = null; modCount += size - w; size = w; modified = true; } } return modified; }
batchRemove不常用方法,可以批量刪除當前list中包含(complement == true)或不包含(complement == false)某個集合c中所有元素。並返回操作的結果。
備註
上面說到了,直接使用ArrayList的remove在遍歷中很容易出錯,下面看看它的迭代器是怎麼實現remove的
private class Itr implements Iterator<E> { int cursor; // index of next element to return int lastRet = -1; // index of last element returned; -1 if no such int expectedModCount = modCount; Itr() {} public boolean hasNext() { return cursor != size; } public void remove() { if (lastRet < 0) throw new IllegalStateException(); checkForComodification(); try { ArrayList.this.remove(lastRet); cursor = lastRet; lastRet = -1; expectedModCount = modCount; } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } } }
cursor記錄要訪問的下一個index,lastRet記錄當前已經讀到的index,迭代器在remove的時候,先呼叫ArrayList的remove方法刪除對應元素,同時,會把cursor和lastRet都減1,自動幫我們完成了元素的重新定位。
本文來自我的個人部落格:http://blog.duchangchun.com/2018/12/29/jdk_arraylist/