ArrayList
是一個其容量可以動態增加
的動態數組java
繼承關係圖:
segmentfault
咱們從源碼角度看一下:數組
public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable{ //默認容量大小 private static final int DEFAULT_CAPACITY = 10; //指定ArrayList容量爲0時返回該數組 private static final Object[] EMPTY_ELEMENTDATA = {}; //當沒有指定ArrayList容量時返回該數組 private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {}; //存放數據 transient Object[] elementData; //ArrayList中元素數量 private int size;
總結dom
10
elementData
數組存放數據注意:能夠看到elementData被transient
標識,表明elementData沒法被序列化,爲何要這麼設置呢?
由於elementData裏面不是全部的元素都有數據,由於容量的問題,elementData裏面有一些元素是空的,這種是沒有必要序列化的。
ArrayList的序列化和反序列化依賴writeObject和readObject方法來實現。能夠避免序列化空的元素。函數
//構造一個初始容量爲10的空數組 public ArrayList() { this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA; } //構造一個具備初始容量值的空數組 public ArrayList(int initialCapacity) { if (initialCapacity > 0) { this.elementData = new Object[initialCapacity]; } else if (initialCapacity == 0) { this.elementData = EMPTY_ELEMENTDATA; } else { throw new IllegalArgumentException("Illegal Capacity: "+initialCapacity); } } //構造一個包含指定元素的數組 public ArrayList(Collection<? extends E> c) { elementData = c.toArray(); if ((size = elementData.length) != 0) { // c.toArray 可能不會返回Object[](註釋是這樣說的),因此這裏要判斷一下類型 if (elementData.getClass() != Object[].class) elementData = Arrays.copyOf(elementData, size, Object[].class); } else { //若是傳入的c長度爲0,則替換成空數組 this.elementData = EMPTY_ELEMENTDATA; } }
構造函數很簡單,這裏就很少說了!ui
/* * 添加元素到集合中 */ public boolean add(E e) { ensureCapacityInternal(size + 1);//判斷ArrayList是否須要擴容 elementData[size++] = e; return true; } /*判斷是否須要擴容——> minCapacity是集合須要的最小容量*/ private void ensureCapacityInternal(int minCapacity) { ensureExplicitCapacity(calculateCapacity(elementData, minCapacity)); } /*返回添加元素後的容量大小*/ private static int calculateCapacity(Object[] elementData, int minCapacity) { //首次添加元素時,返回 minCapacity > 10 ? minCapacity : 10 (首次可能使用addAll方法添加大量元素) if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) { return Math.max(DEFAULT_CAPACITY, minCapacity); } return minCapacity; } /*判斷是否須要擴容*/ private void ensureExplicitCapacity(int minCapacity) { modCount++;//modCount是繼承自AbstractList的變量,用來表示集合被修改的次數 if (minCapacity - elementData.length > 0) grow(minCapacity); } /*擴容*/ private void grow(int minCapacity) { int oldCapacity = elementData.length; int newCapacity = oldCapacity + (oldCapacity >> 1);//擴容爲原來的1.5倍 if (newCapacity - minCapacity < 0)//若是擴容後仍是小於最小容量,則設置minCapacity爲容量大小 newCapacity = minCapacity; if (newCapacity - MAX_ARRAY_SIZE > 0)//MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8 newCapacity = hugeCapacity(minCapacity); //調用Arrays.copyOf生成新數組 elementData = Arrays.copyOf(elementData, newCapacity); } private static int hugeCapacity(int minCapacity) { if (minCapacity < 0) throw new OutOfMemoryError(); return (minCapacity > MAX_ARRAY_SIZE) ? Integer.MAX_VALUE : MAX_ARRAY_SIZE; }
到目前爲止,咱們就能夠知道add(E e)
的基本實現了:
添加元素時,首先去檢查一下數組的容量是否足夠,若是不夠則擴容到原來的1.5
倍
擴容後,若是容量仍是小於minCapacity,就將容量擴充爲minCapacitythis
那如何在指定位置添加元素呢?很簡單,直接看源碼吧spa
/* * 在指定位置添加元素 */ public void add(int index, E element) { rangeCheckForAdd(index);//參數校驗 ensureCapacityInternal(size + 1); System.arraycopy(elementData, index, elementData, index + 1,size - index); elementData[index] = element; size++; } private void rangeCheckForAdd(int index) { if (index > size || index < 0) throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); }
remove(int index)
:根據index計算須要左移的元素個數,調用System.arraycopy()
生成新數組/* * 刪除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; //設爲null讓JVM回收 return oldValue;//返回舊數據 }
remove(Object o)
:遍歷數組後,刪除給定元素/* * 刪除給定Object對象 */ public boolean remove(Object o) { if (o == null) {//刪除null對象-->ArrayList能夠存放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; } //跳過邊界檢查,無返回值 private void fastRemove(int index) { modCount++;//修改次數+1 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 }
removeAll(Collection<?> c)
:把須要移除的數據都替換掉,不須要移除的數據前移/* * 從elementData中移除包含在指定集合中的全部元素 */ public boolean removeAll(Collection<?> c) { Objects.requireNonNull(c);//判空——>if (c == null) throw new NullPointerException(); return batchRemove(c, false); } 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];//w爲最後要保留的元素的數量 } finally { //當遍歷過程當中拋出異常後,確保未遍歷的元素能夠接在後面(由於c.contains可能會拋出異常) if (r != size) { System.arraycopy(elementData, r,elementData, w,size - r); w += size - r; } if (w != size) { //GC回收(後面須要保留的元素已經被移到前面來了,因此直接把w後面的元素設爲null) for (int i = w; i < size; i++) elementData[i] = null; modCount += size - w; size = w; modified = true; } } return modified; }
注意:調用remove刪除元素時不會減小容量,若但願減小容量則調用trimToSize()
code
/* * 獲取index索引對象 */ public E get(int index) { rangeCheck(index);//參數校驗 return elementData(index); } E elementData(int index) { return (E) elementData[index]; }
/* * 設置index索引對象 */ public E set(int index, E element) { rangeCheck(index); E oldValue = elementData(index); elementData[index] = element; return oldValue; }
查找和更新邏輯很簡單,這裏就很少說了對象
接下來看看其它一些輔助函數
contains
判斷集合中是否包含某元素
public boolean contains(Object o) { return indexOf(o) >= 0; }
indexOf
返回指定元素第一次出現的位置
/* * 返回指定元素第一次出現的位置(返回-1表示沒有此元素) * lastIndexOf——>同理(其實就是從後向前遍歷) */ 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; }
toArray
封裝成數組後返回
/*返回Object數組*/ //Java不能對數組進行轉型,Integer[] a = (Integer[]) objects會拋出ClassCastException異常,只能一個一個轉 public Object[] toArray() { return Arrays.copyOf(elementData, size); } /*返回給定類型的數組*/ //Integer[] integers = list.toArray(new Integer[list.size()]); public <T> T[] toArray(T[] a) { if (a.length < size) return (T[]) Arrays.copyOf(elementData, size, a.getClass()); System.arraycopy(elementData, 0, a, 0, size); if (a.length > size) a[size] = null; return a; }
iterator
public Iterator<E> iterator() { return new Itr(); }
Itr
是ArrayList的一個內部類
private class Itr implements Iterator<E> { int cursor; // 下次越過的元素索引 int lastRet = -1; // 上次越過的元素索引 int expectedModCount = modCount;//預期修改次數 Itr() {} /*判斷是否有下一個元素*/ public boolean hasNext() { return cursor != size; } /*向後遍歷並返回越過的元素*/ public E next() { checkForComodification();//fail-fast機制,不容許在遍歷集合時修改元素 int i = cursor; if (i >= size) throw new NoSuchElementException(); Object[] elementData = ArrayList.this.elementData; if (i >= elementData.length) throw new ConcurrentModificationException(); cursor = i + 1;//調用next後cursor+1 return (E) elementData[lastRet = i];//爲lastRet賦值——>i爲調用next後越過的元素索引 } /*刪除上次越過的元素(調用remove前要先調用next)*/ public void remove() { if (lastRet < 0) //lastRet 默認爲-1 throw new IllegalStateException(); checkForComodification();//fail-fast try { ArrayList.this.remove(lastRet);//調用ArrayList.remove刪除元素,這時modCount++ cursor = lastRet; //lastRet 從新設爲-1,因此調用remove前要先調用next爲lastRet賦值 lastRet = -1; //修改expectedModCount //所以當你須要在遍歷時刪除元素時,應該使用iterator.remove,而不是list.remove(iterator.next()); expectedModCount = modCount; } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } } /*操做未遍歷的元素*/ public void forEachRemaining(Consumer<? super E> consumer) {//這裏的consumer是指對剩餘元素的操做 Objects.requireNonNull(consumer);//判空 final int size = ArrayList.this.size; int i = cursor; if (i >= size) { return; } final Object[] elementData = ArrayList.this.elementData; if (i >= elementData.length) { throw new ConcurrentModificationException(); } //對未遍歷的元素進行操做 while (i != size && modCount == expectedModCount) { consumer.accept((E) elementData[i++]); } cursor = i; lastRet = i - 1; checkForComodification(); } //fail-fast final void checkForComodification() { if (modCount != expectedModCount) throw new ConcurrentModificationException(); } }
listIterator
public ListIterator<E> listIterator() { return new ListItr(0); }
ListItr
也是ArrayList的一個內部類,它繼承了Itr
類,新添加了hasPrevious、nextIndex、previousIndex、previous等方法
private class ListItr extends Itr implements ListIterator<E> {//ListIterator<E> extends Iterator<E> //new ListItr(n)表明從n開始遍歷 ListItr(int index) { super(); cursor = index; } /*判斷是否有上一個元素*/ public boolean hasPrevious() { return cursor != 0; } /*返回下一次越過的元素索引*/ public int nextIndex() { return cursor; } /*返回上一次越過的元素索引*/ public int previousIndex() { return cursor - 1; } /*向前遍歷*/ public E previous() { checkForComodification();//fail-fast int i = cursor - 1; if (i < 0) throw new NoSuchElementException(); Object[] elementData = ArrayList.this.elementData; if (i >= elementData.length) throw new ConcurrentModificationException(); cursor = i;//向前遍歷-->cursor-1 return (E) elementData[lastRet = i];//爲lastRet賦值並返回越過的元素 } /*設置元素*/ public void set(E e) { if (lastRet < 0)//這裏也說明了調用set以前要先調用next或previous throw new IllegalStateException(); checkForComodification();//fail-fast try { ArrayList.this.set(lastRet, e);//調用ArrayList.set方法,這裏沒有修改modCount } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } } /*添加元素*/ public void add(E e) { checkForComodification();//fail-fast try { int i = cursor; ArrayList.this.add(i, e);//調用ArrayList.add方法,modCount++ cursor = i + 1; lastRet = -1; expectedModCount = modCount;//從新設置expectedModCount } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } } }
關於ArrayList源碼咱們就看到這裏,若有不當請多指教,對HashMap源碼感興趣的能夠看下我另外一篇:深刻剖析HashMap源碼