package java.util; import java.util.function.Consumer; import java.util.function.Predicate; import java.util.function.UnaryOperator; public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable { private static final long serialVersionUID = 8683452581122892189L; //默認容量 private static final int DEFAULT_CAPACITY = 10; //靜態的一個屬性,全部實例共享屬性,當初始化容量爲0的時候,就使用這個屬性做爲實例底層數組 private static final Object[] EMPTY_ELEMENTDATA = {}; /*根據註釋,這個大概意思就是構造一個空的對象數組,用來與EMPTY_ELEMENTDATA 這個數組進行對比 來肯定當第一次向ArrayList中添加數據時,應該若是進行擴容,就是增長多大的容量。*/ private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {}; //實際上真正保存數據的數組,今後出能夠看出ArrayList使用Object數組來保存數據 transient Object[] elementData; // non-private to simplify nested class access //實際包含元素的個數 private int size; /* 傳遞一個初始化容量的構造函數,會判斷傳遞的參數與0的關係 若是大於0,會在ArrayList內部構建一個長度爲initalCapacity的數組 若是等於0,會將上述的靜態EMPTY_ELEMENTDATA屬性賦值給elementData,也不會產生新的數組。若是小於0,則拋出異常 */ public ArrayList(int initialCapacity) { if (initialCapacity > 0) { this.elementData = new Object[initialCapacity];//注意此處並無將initialCapacity賦值給size } else if (initialCapacity == 0) { this.elementData = EMPTY_ELEMENTDATA; } else { throw new IllegalArgumentException("Illegal Capacity: "+ initialCapacity); } } /* 無參的構造函數,在該構造函數中,會將上述的靜態的DEFAULTCAPACITY_EMPTY_ELEMENTDATA屬性,賦值給elementData屬性 也即咱們用這種方法構造ArraList的時候,並不會真正產生實例化的數組,而是引用一個靜態的空數組 */ public ArrayList() { this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA; } /* 傳遞一個集合給ArrayList,它首先會將集合轉換成數組賦值給elementData 以後判斷數組長度,若是等於0,則將elementData賦值爲EMPTY_ELEMENTDATA 若是不等於0,還須要判斷接受過來的數組(如今是elementData)是不是Object[]類型的 若是不是的化,將它轉換成Object[]類型(根據註釋,toArray方法有可能獲得的不是Object[]類型) */ public ArrayList(Collection<? extends E> c) { elementData = c.toArray(); if ((size = elementData.length) != 0) { // c.toArray might (incorrectly) not return Object[] (see 6260652) if (elementData.getClass() != Object[].class) elementData = Arrays.copyOf(elementData, size, Object[].class); } else { // replace with empty array. this.elementData = EMPTY_ELEMENTDATA; } } /* 本質上是將數組的尾部刪除掉造成新數組 新數組的length與size一致,節約空間 */ public void trimToSize() { modCount++; if (size < elementData.length) { elementData = (size == 0) ? EMPTY_ELEMENTDATA : Arrays.copyOf(elementData, size); } } /* 增長這個ArrayList實例的能力,若是有必要,以確保它至少能容納的最小容量參數指定元素個數。 提供給外界的方法,是的使用者能夠經過這個方法本身去擴容 */ public void ensureCapacity(int minCapacity) { int minExpand = (elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA) // any size if not default element table ? 0 // larger than default for default empty table. It's already // supposed to be at default size. : DEFAULT_CAPACITY;//elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA意味着elementData可能不是一個length爲0的數組 if (minCapacity > minExpand) { ensureExplicitCapacity(minCapacity); } } /* 一個私有方法,確保minCapacity在容量範圍內 若是elementData等於DEFAULTCAPACITY_EMPTY_ELEMENTDATA,則minCapacity會取DEFAULT_CAPACITY, minCapacity中比較大的那個 也即若是minCapacity小於10,則取10,若是大於10,則去minCapacity 隨後要執行ensureExplicitCapacity方法 */ private void ensureCapacityInternal(int minCapacity) { if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) { minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity); } ensureExplicitCapacity(minCapacity); } /* ensureExplicitCapacity要接受一個int類型的參數,意味着最少須要容量爲minCapacity 首先會對modCount+1,modCount是AbstractList類中的一個成員變量,該值表示對List的修改次數,主要是爲了服務快速失敗功能的 隨後若是minCapacity要大於現有數組elementData的長度的化,那麼就執行grow方法,grow是擴容的方法 */ private void ensureExplicitCapacity(int minCapacity) { modCount++; // overflow-conscious code if (minCapacity - elementData.length > 0) grow(minCapacity); } /* 數組所能開闢的最大長度 由於有些虛擬機保留了一些header words在數組中 嘗試要開闢更大的長度的數組,可能會出現OOM異常(在一些虛擬機實現中) */ private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8; /* ArrayList的擴容,接收一個int類型參數,表示至少須要多少容量 */ private void grow(int minCapacity) { // overflow-conscious code int oldCapacity = elementData.length;//獲得目前的容量 //oldCapacity>>1表示除2取整數,該式子最終表示意思爲newCapacity大於爲oldCapacity的1.5倍數 int newCapacity = oldCapacity + (oldCapacity >> 1); //判斷newCapacity是否溢出 if (newCapacity - minCapacity < 0) //溢出:newCapacity等於minCapacity newCapacity = minCapacity; //判斷newCapacity是否超過了MAX_ARRAY_SIZE,超過了,則計算最大容量;具體緣由是由於不一樣虛擬機的實現不一樣 if (newCapacity - MAX_ARRAY_SIZE > 0) newCapacity = hugeCapacity(minCapacity); //執行Arrays.copyOf方法,傳遞原數組與新數組長度,由Arrays內部建立數組返回並接受給elementData elementData = Arrays.copyOf(elementData, newCapacity); } /* 求出最大的容量值,首先判斷minCapacity是否已經溢出了,溢出了就直接拋出OOM 不然就去判斷minCapacity 是否大於 MAX_ARRAY_SIZE 大於返回 Integer.MAX_VALUE ,不大於 返回MAX_ARRAY_SIZE */ private static int hugeCapacity(int minCapacity) { if (minCapacity < 0) // overflow throw new OutOfMemoryError(); return (minCapacity > MAX_ARRAY_SIZE) ? Integer.MAX_VALUE : MAX_ARRAY_SIZE; } //獲得size,size是真正的保存的元素的數量 public int size() { return size; } //判斷容器是否爲空(指是不包含元素) public boolean isEmpty() { return size == 0; } //判斷容器是否包含某個元素 public boolean contains(Object o) { return indexOf(o) >= 0; } //indexOf是來得到o元素(包括null)在容器中的位置的,位置從0開始到size-1結束,若是返回-1表示不包含 //對於重複的元素,只獲取第一個所在的位置 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; } //與indexOf功能同樣,可是確實得到重複元素的最後一個位置 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; } //重寫了Object中的clone方法,用於賦值容器,淺複製 public Object clone() { try { ArrayList<?> v = (ArrayList<?>) 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(e); } } //獲得數組的副本 public Object[] toArray() { return Arrays.copyOf(elementData, size); } /* 給定一個指定數組,返回指定數組大小,類型的副本 */ @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);//此處是size == a.length if (a.length > size) a[size] = null;//若是a.length>size,則截取size的長度,可是若是a自己就是有數據的,可能會出現a[size+?]有數據,而a[size]爲null return a; } // Positional Access Operations //不須要檢查index的快速訪問元素,可是是包權限,只容許內部使用 @SuppressWarnings("unchecked") E elementData(int index) { return (E) elementData[index]; } /* 判斷一下是否index是否越界 而後經過快速訪問來返回元素 */ public E get(int index) { rangeCheck(index); return elementData(index); } /* 判斷一下是否越界 而後獲得處於index位置的原元素,隨後將index位置置入新元素 返回原來的元素 要求 index<size */ public E set(int index, E element) { rangeCheck(index); E oldValue = elementData(index); elementData[index] = element; return oldValue; } /* 集合中新增一個元素,首先要確保在承受能力範圍內 以後將新加入進來的元素賦值到數組的第size的位置上 隨後size+1 新增的元素,插入到數組的末尾 */ public boolean add(E e) { ensureCapacityInternal(size + 1); // Increments modCount!! elementData[size++] = e; return true; } /* 插入一個元素element到指定index位置,原位置的元素依次向後移動一位 改方法效率要低一些,若是並非特定必需要塞入哪一個位置的話,最好不要用 */ public void add(int index, E element) { //首先會去檢查一下index是否可使用 rangeCheckForAdd(index); //確保數組可容納 ensureCapacityInternal(size + 1); // Increments modCount!! 會修改modCount的值,modCount+1 //隨後調用System.arraycopy方法,將elementData的index位置元素依次向後移動,爲接下來的插入預留空間 System.arraycopy(elementData, index, elementData, index + 1, size - index); elementData[index] = element;//真正的插入操做 size++;//size+1 } /* 刪除指定位置的元素,若是index>size的話,會出現數組越界 */ public E remove(int index) { rangeCheck(index);//index>size throw IndexOutOfBoundsException modCount++; E oldValue = elementData(index);//獲得原來elementData中的元素 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;//返回被刪除的元素 } /* 刪除某一個元素,傳入要被刪除的元素 */ public boolean remove(Object o) { if (o == null) {//刪除null元素 for (int index = 0; index < size; index++)//迭代ArrayList if (elementData[index] == null) {//若是在size以前的位置有存在空元素 fastRemove(index);//則快速刪除(所謂快速刪除,就是不去作越界檢查以及不返回結果,徹底給本類本身使用的private方法) return true; } } else {//刪除非空元素,與刪除null元素邏輯相同 for (int index = 0; index < size; index++) if (o.equals(elementData[index])) {//此處使用equals方法來進行比較,因此在使用remove(Object o)的時候,要考慮是否重寫了equals方法 fastRemove(index);//fastRemove也是會移動數組的,若是有刪除重複元素的時候,效率很低 return true; } } return false; } /* 快速刪除 不作index檢查,只容許內部使用 */ private void fastRemove(int index) { modCount++; 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 } /* 清除數組,全部元素置爲null */ public void clear() { modCount++; // clear to let GC do its work for (int i = 0; i < size; i++) elementData[i] = null; size = 0; } /* 添加一次性add多個元素,接受參數爲集合類型 */ public boolean addAll(Collection<? extends E> c) { Object[] a = c.toArray(); int numNew = a.length;//可能會產生空指針錯誤 ensureCapacityInternal(size + numNew); // Increments modCount //將a數組插入到elementData的size位置 System.arraycopy(a, 0, elementData, size, numNew); size += numNew; return numNew != 0; } /* 指定index位置插入多個元素,原來位置的元素依次向後移動 index不能大於size,若是大於size會產生數組越界 */ 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; } /* 範圍刪除,刪除從fromIndex~toIndex,包含fromIndex,不包含toIndex */ protected void removeRange(int fromIndex, int toIndex) { modCount++; int numMoved = size - toIndex; System.arraycopy(elementData, toIndex, elementData, fromIndex, numMoved); // clear to let GC do its work int newSize = size - (toIndex-fromIndex); for (int i = newSize; i < size; i++) { elementData[i] = null; } size = newSize; } //index檢查判斷,專門封裝起來是由於不少地方使用 private void rangeCheck(int index) { if (index >= size) throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); } //專門爲add方法封裝的rangeCheck方法 private void rangeCheckForAdd(int index) { if (index > size || index < 0) throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); } //爲IndexOutOfBoundsException提供信息的方法,告訴哪一個位置出現了數組越界 private String outOfBoundsMsg(int index) { return "Index: "+index+", Size: "+size; } //一次性刪除多個元素 public boolean removeAll(Collection<?> c) { Objects.requireNonNull(c);//判斷c是否爲空,爲空拋出異常 return batchRemove(c, false);//批量刪除 } //保留當前容器與c的並集,並返回 public boolean retainAll(Collection<?> c) { Objects.requireNonNull(c); return batchRemove(c, true); } //批量刪除方法,complement爲true表示求交集,若是爲false表示在elementData中保留原有的非c的集合 //也即true: a屬於elementData同時a屬於c; false: a屬於elementData同時a不屬於c private boolean batchRemove(Collection<?> c, boolean complement) { final Object[] elementData = this.elementData; int r = 0, w = 0;//一個讀的index,一個是寫的index 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) {//只移動一次數組,比單獨remove效果要好 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;//從新定義size modified = true; } } return modified; } //保存數組實例的狀態到一個流(即它序列化) private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException{ // Write out element count, and any hidden stuff int expectedModCount = modCount; s.defaultWriteObject(); // Write out size as capacity for behavioural compatibility with clone() s.writeInt(size); // Write out all elements in the proper order. for (int i=0; i<size; i++) { s.writeObject(elementData[i]); } if (modCount != expectedModCount) { throw new ConcurrentModificationException(); } } //從一個流中讀出數組實例的狀態 private void readObject(java.io.ObjectInputStream s) throws java.io.IOException, ClassNotFoundException { elementData = EMPTY_ELEMENTDATA; // Read in size, and any hidden stuff s.defaultReadObject(); // Read in capacity s.readInt(); // ignored if (size > 0) { // be like clone(), allocate array based upon size not capacity ensureCapacityInternal(size); Object[] a = elementData; // Read in all elements in the proper order. for (int i=0; i<size; i++) { a[i] = s.readObject(); } } } //返回一個list迭代器,鏈表迭代器,能夠雙向迭代,而且還具備add方法,可是隻有在list類型中才可使用,別的集合類沒有 //接受一個Index,肯定迭代器初始的位置 public ListIterator<E> listIterator(int index) { if (index < 0 || index > size)//先判斷index是否合法 throw new IndexOutOfBoundsException("Index: "+index); return new ListItr(index); } /** * Returns a list iterator over the elements in this list (in proper * sequence). * * <p>The returned list iterator is <a href="#fail-fast"><i>fail-fast</i></a>. * * @see #listIterator(int) */ public ListIterator<E> listIterator() { return new ListItr(0); } /** * Returns an iterator over the elements in this list in proper sequence. * * <p>The returned iterator is <a href="#fail-fast"><i>fail-fast</i></a>. * * @return an iterator over the elements in this list in proper sequence */ public Iterator<E> iterator() { return new Itr(); } /** * An optimized version of AbstractList.Itr * AbstractList.Itr的優化版本迭代器 */ private class Itr implements Iterator<E> { int cursor; // 下一個要被返回元素的下標 int lastRet = -1; // 上一個被返回的元素的下標,若是沒有的話默認爲-1 int expectedModCount = modCount; //判斷是否還有下一個元素 public boolean hasNext() { return cursor != size; } //返回下一個元素,默認一開始的next是第一個元素 @SuppressWarnings("unchecked") public E next() { checkForComodification();//快速失敗 int i = cursor; if (i >= size)//會判斷一次位置是否合法,由於cursor只是盲目的+1 throw new NoSuchElementException(); Object[] elementData = ArrayList.this.elementData; if (i >= elementData.length) throw new ConcurrentModificationException(); cursor = i + 1;//cursor設置爲下一個要被返回的元素下標 return (E) elementData[lastRet = i];//將lastRet設置爲被返回的元素下標 } //刪除上一個元素,也即最近被next()出來的元素 public void remove() { if (lastRet < 0) throw new IllegalStateException(); checkForComodification(); try { ArrayList.this.remove(lastRet);//刪除的是下標爲lastRet元素 cursor = lastRet;//回退 lastRet = -1;//設置成爲-1,也即不能連續的刪除,該類不可以往回走,只能繼續前進,由於繼續刪除,會拋出IllegalStateException異常 expectedModCount = modCount; } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } } /* 遍歷餘下的元素 */ @Override @SuppressWarnings("unchecked") public void forEachRemaining(Consumer<? super E> consumer) { Objects.requireNonNull(consumer);//判斷consumer不能爲null 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++]);//此處接受elementData元素,執行consumer中的方法,可能會去改變elementData元素 } // update once at end of iteration to reduce heap write traffic cursor = i; lastRet = i - 1; checkForComodification(); } final void checkForComodification() { if (modCount != expectedModCount) throw new ConcurrentModificationException(); } } /** * An optimized version of AbstractList.ListItr * 一個對AbstractList.ListItr的優化版本鏈表迭代器 */ private class ListItr extends Itr implements ListIterator<E> { ListItr(int index) { super(); cursor = index; } public boolean hasPrevious() { return cursor != 0; } public int nextIndex() { return cursor; } public int previousIndex() { return cursor - 1; } //返回上一個元素 @SuppressWarnings("unchecked") public E previous() { checkForComodification(); int i = cursor - 1; if (i < 0) throw new NoSuchElementException(); Object[] elementData = ArrayList.this.elementData; if (i >= elementData.length) throw new ConcurrentModificationException(); cursor = i; return (E) elementData[lastRet = i]; } //更新上一個位置的元素,將其置換成e public void set(E e) { if (lastRet < 0) throw new IllegalStateException(); checkForComodification(); try { ArrayList.this.set(lastRet, e); } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } } //新增一個元素,處在上一個元素以後,下一個元素以前,會移動數組 public void add(E e) { checkForComodification(); try { int i = cursor; ArrayList.this.add(i, e); cursor = i + 1; lastRet = -1; expectedModCount = modCount; } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } } } //獲得子列表 從fromIndex~toIndex位置 public List<E> subList(int fromIndex, int toIndex) { subListRangeCheck(fromIndex, toIndex, size); return new SubList(this, 0, fromIndex, toIndex); } //判斷Index是否合法 static void subListRangeCheck(int fromIndex, int toIndex, int size) { if (fromIndex < 0) throw new IndexOutOfBoundsException("fromIndex = " + fromIndex); if (toIndex > size) throw new IndexOutOfBoundsException("toIndex = " + toIndex); if (fromIndex > toIndex) throw new IllegalArgumentException("fromIndex(" + fromIndex + ") > toIndex(" + toIndex + ")"); } //繼承與AbstractList的SubList類,其實這個類,只是去封裝了幾個屬性,實際上用的仍是原來ArrayList類的數組,外觀模式 private class SubList extends AbstractList<E> implements RandomAccess { private final AbstractList<E> parent; private final int parentOffset; private final int offset; int size; //參數: //parent 父類型 //offset 父類型的偏移量 //fromIndex 子列表的開始元素,位於父列表的位置 //toIndex 子列表的結束元素,位於父列表的位置 SubList(AbstractList<E> parent, int offset, int fromIndex, int toIndex) { this.parent = parent; this.parentOffset = fromIndex; this.offset = offset + fromIndex; this.size = toIndex - fromIndex; this.modCount = ArrayList.this.modCount; } public E set(int index, E e) { rangeCheck(index); checkForComodification(); E oldValue = ArrayList.this.elementData(offset + index); ArrayList.this.elementData[offset + index] = e; return oldValue; } public E get(int index) { rangeCheck(index); checkForComodification(); return ArrayList.this.elementData(offset + index); } public int size() { checkForComodification(); return this.size; } public void add(int index, E e) { rangeCheckForAdd(index); checkForComodification(); parent.add(parentOffset + index, e); this.modCount = parent.modCount; this.size++; } public E remove(int index) { rangeCheck(index); checkForComodification(); E result = parent.remove(parentOffset + index); this.modCount = parent.modCount; this.size--; return result; } protected void removeRange(int fromIndex, int toIndex) { checkForComodification(); parent.removeRange(parentOffset + fromIndex, parentOffset + toIndex); this.modCount = parent.modCount; this.size -= toIndex - fromIndex; } public boolean addAll(Collection<? extends E> c) { return addAll(this.size, c); } public boolean addAll(int index, Collection<? extends E> c) { rangeCheckForAdd(index); int cSize = c.size(); if (cSize==0) return false; checkForComodification(); parent.addAll(parentOffset + index, c); this.modCount = parent.modCount; this.size += cSize; return true; } public Iterator<E> iterator() { return listIterator(); } public ListIterator<E> listIterator(final int index) { checkForComodification(); rangeCheckForAdd(index); final int offset = this.offset; return new ListIterator<E>() { int cursor = index; int lastRet = -1; int expectedModCount = ArrayList.this.modCount; public boolean hasNext() { return cursor != SubList.this.size; } @SuppressWarnings("unchecked") public E next() { checkForComodification(); int i = cursor; if (i >= SubList.this.size) throw new NoSuchElementException(); Object[] elementData = ArrayList.this.elementData; if (offset + i >= elementData.length) throw new ConcurrentModificationException(); cursor = i + 1; return (E) elementData[offset + (lastRet = i)]; } public boolean hasPrevious() { return cursor != 0; } @SuppressWarnings("unchecked") public E previous() { checkForComodification(); int i = cursor - 1; if (i < 0) throw new NoSuchElementException(); Object[] elementData = ArrayList.this.elementData; if (offset + i >= elementData.length) throw new ConcurrentModificationException(); cursor = i; return (E) elementData[offset + (lastRet = i)]; } @SuppressWarnings("unchecked") public void forEachRemaining(Consumer<? super E> consumer) { Objects.requireNonNull(consumer); final int size = SubList.this.size; int i = cursor; if (i >= size) { return; } final Object[] elementData = ArrayList.this.elementData; if (offset + i >= elementData.length) { throw new ConcurrentModificationException(); } while (i != size && modCount == expectedModCount) { consumer.accept((E) elementData[offset + (i++)]); } // update once at end of iteration to reduce heap write traffic lastRet = cursor = i; checkForComodification(); } public int nextIndex() { return cursor; } public int previousIndex() { return cursor - 1; } public void remove() { if (lastRet < 0) throw new IllegalStateException(); checkForComodification(); try { SubList.this.remove(lastRet); cursor = lastRet; lastRet = -1; expectedModCount = ArrayList.this.modCount; } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } } public void set(E e) { if (lastRet < 0) throw new IllegalStateException(); checkForComodification(); try { ArrayList.this.set(offset + lastRet, e); } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } } public void add(E e) { checkForComodification(); try { int i = cursor; SubList.this.add(i, e); cursor = i + 1; lastRet = -1; expectedModCount = ArrayList.this.modCount; } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } } final void checkForComodification() { if (expectedModCount != ArrayList.this.modCount) throw new ConcurrentModificationException(); } }; } public List<E> subList(int fromIndex, int toIndex) { subListRangeCheck(fromIndex, toIndex, size); return new SubList(this, offset, fromIndex, toIndex); } private void rangeCheck(int index) { if (index < 0 || index >= this.size) throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); } private void rangeCheckForAdd(int index) { if (index < 0 || index > this.size) throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); } private String outOfBoundsMsg(int index) { return "Index: "+index+", Size: "+this.size; } private void checkForComodification() { if (ArrayList.this.modCount != this.modCount) throw new ConcurrentModificationException(); } public Spliterator<E> spliterator() { checkForComodification(); return new ArrayListSpliterator<E>(ArrayList.this, offset, offset + this.size, this.modCount); } } //與forEachRemaining很像,一個是迭代全部,一個是迭代剩餘,都會去執行Consumer中定義的方法,可能會改變元素的值 @Override public void forEach(Consumer<? super E> action) { Objects.requireNonNull(action); final int expectedModCount = modCount; @SuppressWarnings("unchecked") final E[] elementData = (E[]) this.elementData; final int size = this.size; for (int i=0; modCount == expectedModCount && i < size; i++) { action.accept(elementData[i]); } if (modCount != expectedModCount) { throw new ConcurrentModificationException(); } } //返回spliterator,用於並行計算中,splitable iterator可分割迭代器 @Override public Spliterator<E> spliterator() { return new ArrayListSpliterator<>(this, 0, -1, 0); } static final class ArrayListSpliterator<E> implements Spliterator<E> { private final ArrayList<E> list;//原數組 private int index; // current index, modified on advance/split private int fence; // -1 until used; then one past last index private int expectedModCount; // initialized when fence set /** Create new spliterator covering the given range */ ArrayListSpliterator(ArrayList<E> list, int origin, int fence, int expectedModCount) { this.list = list; // OK if null unless traversed this.index = origin; this.fence = fence; this.expectedModCount = expectedModCount; } private int getFence() { // 第一次使用時,初始化fence大小 int hi; // (a specialized variant appears in method forEach) ArrayList<E> lst; if ((hi = fence) < 0) { //-1表示初始化的值 if ((lst = list) == null) hi = fence = 0; else { expectedModCount = lst.modCount; hi = fence = lst.size; } } return hi; } //這就是爲Spliterator專門設計的方法,區分與普通的Iterator,該方法會把當前元素劃分一部分出去建立一個新的Spliterator做爲返回, //兩個Spliterator變會並行執行,若是元素個數小到沒法劃分則返回null public ArrayListSpliterator<E> trySplit() { int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;//因爲lo + hi都是整數,>>>至關於除2 return (lo >= mid) ? null : // divide range in half unless too small new ArrayListSpliterator<E>(list, lo, index = mid,//注意index=min expectedModCount); } //tryAdvance就是順序處理每一個元素,相似Iterator,若是還有元素要處理,則返回true,不然返回false public boolean tryAdvance(Consumer<? super E> action) { if (action == null) throw new NullPointerException(); int hi = getFence(), i = index; if (i < hi) { index = i + 1; @SuppressWarnings("unchecked") E e = (E)list.elementData[i]; action.accept(e); if (list.modCount != expectedModCount) throw new ConcurrentModificationException(); return true; } return false; } public void forEachRemaining(Consumer<? super E> action) { int i, hi, mc; // hoist accesses and checks from loop ArrayList<E> lst; Object[] a; if (action == null) throw new NullPointerException(); if ((lst = list) != null && (a = lst.elementData) != null) { if ((hi = fence) < 0) { mc = lst.modCount; hi = lst.size; } else mc = expectedModCount; if ((i = index) >= 0 && (index = hi) <= a.length) { for (; i < hi; ++i) { @SuppressWarnings("unchecked") E e = (E) a[i]; action.accept(e); } if (lst.modCount == mc) return; } } throw new ConcurrentModificationException(); } //該方法用於估算還剩下多少個元素須要遍歷 public long estimateSize() { return (long) (getFence() - index); } //其實就是表示該Spliterator有哪些特性,用於能夠更好控制和優化Spliterator的使用 public int characteristics() { return Spliterator.ORDERED | Spliterator.SIZED | Spliterator.SUBSIZED; } } //刪除,增長過濾功能 @Override public boolean removeIf(Predicate<? super E> filter) { Objects.requireNonNull(filter);//判斷過濾器是否爲空 // figure out which elements are to be removed // any exception thrown from the filter predicate at this stage // will leave the collection unmodified int removeCount = 0;//要刪除元素的個數 final BitSet removeSet = new BitSet(size);//使用BitSet類來保存要被刪除的Set,BitSet是使用位圖來保存數據,節省很大內存 final int expectedModCount = modCount;//預期的modCount final int size = this.size; for (int i=0; modCount == expectedModCount && i < size; i++) { @SuppressWarnings("unchecked") final E element = (E) elementData[i]; if (filter.test(element)) {//若是element匹配filter中的過濾條件的話,則會返回true removeSet.set(i);//使用位圖來保存要被刪除的index removeCount++; } } if (modCount != expectedModCount) {//快速失敗機制,在多線程狀況下,去報錯,引發程序員注意 throw new ConcurrentModificationException(); } // shift surviving elements left over the spaces left by removed elements final boolean anyToRemove = removeCount > 0;//用於記錄是否須要刪除 if (anyToRemove) { //須要刪除... final int newSize = size - removeCount;//計算剩餘的長度,也即新數組的長度 for (int i=0, j=0; (i < size) && (j < newSize); i++, j++) {//(i < size) && (j < newSize)會節約一些效率 i = removeSet.nextClearBit(i);//獲得沒有被攔截的index elementData[j] = elementData[i]; } for (int k=newSize; k < size; k++) {//清除數組後面的多餘引用,GC elementData[k] = null; // Let gc do its work } this.size = newSize; if (modCount != expectedModCount) { throw new ConcurrentModificationException(); } modCount++;//用於記錄本條數據也改變了數組結構,從這個地方能夠看出來,快速失敗機制並不能徹底確保必定會提醒到程序員,只是有可能 } return anyToRemove; } //替換全部 @Override @SuppressWarnings("unchecked") public void replaceAll(UnaryOperator<E> operator) { Objects.requireNonNull(operator); final int expectedModCount = modCount; final int size = this.size; for (int i=0; modCount == expectedModCount && i < size; i++) { elementData[i] = operator.apply((E) elementData[i]); } if (modCount != expectedModCount) { throw new ConcurrentModificationException(); } modCount++; } @Override @SuppressWarnings("unchecked") public void sort(Comparator<? super E> c) { final int expectedModCount = modCount; Arrays.sort((E[]) elementData, 0, size, c); if (modCount != expectedModCount) { throw new ConcurrentModificationException(); } modCount++; } }