ArrayList源码分析
                                                            生活随笔
收集整理的這篇文章主要介紹了
                                ArrayList源码分析
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.                        
                                
                            
                            
                            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;/*** 一個空數組* 當用戶指定該 ArrayList 容量為 0 時,返回該空數組*/private static final Object[] EMPTY_ELEMENTDATA = {};/*** 一個空數組實例* - 當用戶沒有指定 ArrayList 的容量時(即調用無參構造函數),返回的是該數組==>剛創建一個 ArrayList 時,其內數據量為 0。* - 當用戶第一次添加元素時,該數組將會擴容,變成默認容量為 10(DEFAULT_CAPACITY) 的一個數組===>通過  ensureCapacityInternal() 實現* 它與 EMPTY_ELEMENTDATA 的區別就是:該數組是默認返回的,而后者是在用戶指定容量為 0 時返回*/private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};/*** ArrayList基于數組實現,用該數組保存數據, ArrayList 的容量就是該數組的長度* - 該值為 DEFAULTCAPACITY_EMPTY_ELEMENTDATA 時,當第一次添加元素進入 ArrayList 中時,數組將擴容值 DEFAULT_CAPACITY(10)*/transient Object[] elementData; // non-private to simplify nested class access/*** ArrayList實際存儲的數據數量*/private int size;/*** 創建一個初試容量的、空的ArrayList* @param  initialCapacity  初始容量* @throws IllegalArgumentException 當初試容量值非法(小于0)時拋出*/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);}}/*** 無參構造函數:* - 創建一個 空的 ArrayList,此時其內數組緩沖區 elementData = {}, 長度為 0* - 當元素第一次被加入時,擴容至默認容量 10*/public ArrayList() {this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;}/*** 創建一個包含collection的ArrayList* @param c 要放入 ArrayList 中的集合,其內元素將會全部添加到新建的 ArrayList 實例中* @throws NullPointerException 當參數 c 為 null 時拋出異常*/public ArrayList(Collection<? extends E> c) {//將集合轉化成Object[]數組elementData = c.toArray();//把轉化后的Object[]數組長度賦值給當前ArrayList的size,并判斷是否為0if ((size = elementData.length) != 0) {// c.toArray might (incorrectly) not return Object[] (see 6260652)// 這句話意思是:c.toArray 可能不會返回 Object[],可以查看 java 官方編號為 6260652 的 bugif (elementData.getClass() != Object[].class)// 若 c.toArray() 返回的數組類型不是 Object[],則利用 Arrays.copyOf(); 來構造一個大小為 size 的 Object[] 數組elementData = Arrays.copyOf(elementData, size, Object[].class);} else {// 替換空數組this.elementData = EMPTY_ELEMENTDATA;}}/*** 調整elementData數組的長度,將數組緩沖區大小調整到實際 ArrayList 存儲元素的大小,即 elementData = Arrays.copyOf(elementData, size);* - 該方法由用戶手動調用,以減少空間資源浪費的目的 ce.*/public void trimToSize() {// modCount 是 AbstractList 的屬性值:protected transient int modCount = 0;/*modCount 用來記錄 ArrayList 結構發生變化的次數。結構發生變化是指添加或者刪除至少一個元素的所有操作,或者是調整內部數組的大小,僅僅只是設置元素的值不算結構發生變化。在進行序列化或者迭代等操作時,需要比較操作前后 modCount 是否改變,如果改變了需要拋出 ConcurrentModificationException。*/modCount++;// 當實際大小 < 數組緩沖區大小時// 如調用默認構造函數后,剛添加一個元素,此時 elementData.length = 10,而 size = 1// 通過這一步,可以使得空間得到有效利用,而不會出現資源浪費的情況if (size < elementData.length) {// 調整數組緩沖區 elementData,變為實際存儲大小 Arrays.copyOf(elementData, size)//先判斷size是否為0,如果為0:實際存儲為EMPTY_ELEMENTDATA,如果有數據就是Arrays.copyOf(elementData, size)elementData = (size == 0)? EMPTY_ELEMENTDATA: Arrays.copyOf(elementData, size);}}/*** 指定 ArrayList 的容量* @param   minCapacity   指定的最小容量*/public void ensureCapacity(int minCapacity) {// 最小擴充容量,默認是 10//這句就是:判斷是不是空的ArrayList,如果是的最小擴充容量10,否則最小擴充量為0//上面無參構造函數創建后,當元素第一次被加入時,擴容至默認容量 10,就是靠這句代碼int minExpand = (elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA)? 0: DEFAULT_CAPACITY;// 若用戶指定的最小容量 > 最小擴充容量,則以用戶指定的為準,否則還是 10if (minCapacity > minExpand) {ensureExplicitCapacity(minCapacity);}}/*** 私有方法:明確 ArrayList 的容量,提供給本類使用的方法* - 用于內部優化,保證空間資源不被浪費:尤其在 add() 方法添加時起效* @param minCapacity    指定的最小容量*/private void ensureCapacityInternal(int minCapacity) {// 若 elementData == {},則取 minCapacity 為 默認容量和參數 minCapacity 之間的最大值// 注:ensureCapacity() 是提供給用戶使用的方法,在 ArrayList 的實現中并沒有使用if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {minCapacity= Math.max(DEFAULT_CAPACITY, minCapacity);}ensureExplicitCapacity(minCapacity);}/*** 私有方法:明確 ArrayList 的容量* - 用于內部優化,保證空間資源不被浪費:尤其在 add() 方法添加時起效* @param minCapacity    指定的最小容量*/private void ensureExplicitCapacity(int minCapacity) {// 將“修改統計數”+1,該變量主要是用來實現fail-fast機制的modCount++;// 防止溢出代碼:確保指定的最小容量 > 數組緩沖區當前的長度// overflow-conscious codeif (minCapacity - elementData.length > 0)grow(minCapacity);}/*** 數組緩沖區最大存儲容量* - 一些 VM 會在一個數組中存儲某些數據--->為什么要減去 8 的原因* - 嘗試分配這個最大存儲容量,可能會導致 OutOfMemoryError(當該值 > VM 的限制時)*/private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;/*** 私有方法:擴容,以確保 ArrayList 至少能存儲 minCapacity 個元素* - 擴容計算:newCapacity = oldCapacity + (oldCapacity >> 1);  擴充當前容量的1.5倍* @param minCapacity    指定的最小容量*/private void grow(int minCapacity) {// 防止溢出代碼int oldCapacity = elementData.length;// 運算符 >> 是帶符號右移. 如 oldCapacity = 10,則 newCapacity = 10 + (10 >> 1) = 10 + 5 = 15int newCapacity = oldCapacity + (oldCapacity >> 1);if (newCapacity - minCapacity < 0)  // 若 newCapacity 依舊小于 minCapacitynewCapacity = minCapacity;if (newCapacity - MAX_ARRAY_SIZE > 0)   // 若 newCapacity 大于最大存儲容量,則進行大容量分配newCapacity = hugeCapacity(minCapacity);// minCapacity is usually close to size, so this is a win:elementData = Arrays.copyOf(elementData, newCapacity);}/*** 私有方法:大容量分配,最大分配 Integer.MAX_VALUE* @param minCapacity*/private static int hugeCapacity(int minCapacity) {if (minCapacity < 0) // overflowthrow new OutOfMemoryError();return (minCapacity > MAX_ARRAY_SIZE) ?Integer.MAX_VALUE :MAX_ARRAY_SIZE;}/*** 返回ArrayList實際存儲的元素數量*/public int size() {return size;}/*** ArrayList是否有元素*/public boolean isEmpty() {return size == 0;}/*** 是否包含o元素*/public boolean contains(Object o) {// 根據 indexOf() 的值(索引值)來判斷,大于等于 0 就包含// 注意:等于 0 的情況不能漏,因為索引號是從 0 開始計數的return indexOf(o) >= 0;}/*** 順序查找,返回元素的最低索引值(最首先出現的索引位置)* @return 存在?最低索引值:-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;}/*** 逆序查找,返回元素的最低索引值(最首先出現的索引位置)* @return 存在?最低索引值:-1*/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;}/*** 實現的有Cloneable接口,深度復制:對拷貝出來的 ArrayList 對象的操作,不會影響原來的 ArrayList* @return 一個克隆的 ArrayList 實例(深度復制的結果)*/public Object clone() {try {// Object 的克隆方法:會復制本對象及其內所有基本類型成員和 String 類型成員,但不會復制對象成員、引用對象ArrayList<?> v = (ArrayList<?>) super.clone();// 對需要進行復制的引用變量,進行獨立的拷貝:將存儲的元素移入新的 ArrayList 中v.elementData = Arrays.copyOf(elementData, size);v.modCount = 0;return v;} catch (CloneNotSupportedException e) {// this shouldn't happen, since we are Cloneablethrow new InternalError(e);}}/*** 返回 ArrayList 的 Object 數組* - 包含 ArrayList 的所有儲存元素* - 對返回的該數組進行操作,不會影響該 ArrayList(相當于分配了一個新的數組)==>該操作是安全的* - 元素存儲順序與 ArrayList 中的一致*/public Object[] toArray() {return Arrays.copyOf(elementData, size);}/*** 返回 ArrayList 元素組成的數組* @param a 需要存儲 list 中元素的數組* 若 a.length >= list.size,則將 list 中的元素按順序存入 a 中,然后 a[list.size] = null, a[list.size + 1] 及其后的元素依舊是 a 的元素* 否則,將返回包含list 所有元素且數組長度等于 list 中元素個數的數組* 注意:若 a 中本來存儲有元素,則 a 會被 list 的元素覆蓋,且 a[list.size] = null* @return* @throws ArrayStoreException 當 a.getClass() != list 中存儲元素的類型時* @throws NullPointerException 當 a 為 null 時*/@SuppressWarnings("unchecked")public <T> T[] toArray(T[] a) {// 若數組a的大小 < ArrayList的元素個數,則新建一個T[]數組,// 數組大小是"ArrayList的元素個數",并將“ArrayList”全部拷貝到新數組中if (a.length < size)// Make a new array of a's runtime type, but my contents:return (T[]) Arrays.copyOf(elementData, size, a.getClass());// 若數組a的大小 >= ArrayList的元素個數,則將ArrayList的全部元素都拷貝到數組a中。System.arraycopy(elementData, 0, a, 0, size);if (a.length > size)a[size] = null;return a;}/*** 獲取指定位置上的元素,從0開始*/public E get(int index) {rangeCheck(index);//檢查是否越界return elementData(index);}/*** 檢查數組是否在界線內*/private void rangeCheck(int index) {if (index >= size)throw new IndexOutOfBoundsException(outOfBoundsMsg(index));}/*** 返回在索引為 index 的元素:數組的隨機訪問* - 默認包訪問權限** 封裝粒度很強,連數組隨機取值都封裝為一個方法。* 主要是避免每次取值都要強轉===>設置值就沒有封裝成一個方法,因為設置值不需要強轉* @param index* @return*/@SuppressWarnings("unchecked")E elementData(int index) {return (E) elementData[index];}/*** 設置 index 位置元素的值* @param index 索引值* @param element 需要存儲在 index 位置的元素值* @return 替換前在 index 位置的元素值* @throws IndexOutOfBoundsException {@inheritDoc}*/public E set(int index, E element) {rangeCheck(index);//越界檢查E oldValue = elementData(index);//獲取舊數值elementData[index] = element;return oldValue;}/***增加指定的元素到ArrayList的最后位置* @param e 要添加的元素* @return*/public boolean add(E e) {// 確定ArrayList的容量大小---嚴謹// 注意:size + 1,保證資源空間不被浪費,// ☆☆☆按當前情況,保證要存多少個元素,就只分配多少空間資源ensureCapacityInternal(size + 1);  // Increments modCount!!elementData[size++] = e;return true;}/****在這個ArrayList中的指定位置插入指定的元素,*  - 在指定位置插入新元素,原先在 index 位置的值往后移動一位* @param index 指定位置* @param element 指定元素* @throws IndexOutOfBoundsException*/public void add(int index, E element) {rangeCheckForAdd(index);//判斷角標是否越界//看上面的,size+1,保證資源空間不浪費,按當前情況,保證要存多少元素,就只分配多少空間資源ensureCapacityInternal(size + 1);  // Increments modCount!!//第一個是要復制的數組,第二個是從要復制的數組的第幾個開始,// 第三個是復制到那,四個是復制到的數組第幾個開始,最后一個是復制長度System.arraycopy(elementData, index, elementData, index + 1,size - index);elementData[index] = element;size++;}/*** 移除指定位置的元素* index 之后的所有元素依次左移一位* @param index 指定位置* @return 被移除的元素* @throws IndexOutOfBoundsException*/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;return oldValue;}/*** 移除list中指定的第一個元素(符合條件索引最低的)* 如果list中不包含這個元素,這個list不會改變* 如果包含這個元素,index 之后的所有元素依次左移一位* @param o 這個list中要被移除的元素* @return*/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;}/*** 快速刪除第 index 個元素* 和public E remove(int index)相比* 私有方法,跳過檢查,不返回被刪除的值* @param index 要刪除的腳標*/private void fastRemove(int index) {modCount++;//這個地方改變了modCount的值了int numMoved = size - index - 1;//移動的個數if (numMoved > 0)System.arraycopy(elementData, index+1, elementData, index,numMoved);elementData[--size] = null; //將最后一個元素清除}/*** 移除list中的所有元素,這個list表將在調用之后置空* - 它會將數組緩沖區所以元素置為 null* - 清空后,我們直接打印 list,卻只會看見一個 [], 而不是 [null, null, ….] ==> toString() 和 迭代器進行了處理*/public void clear() {modCount++;// clear to let GC do its workfor (int i = 0; i < size; i++)elementData[i] = null;size = 0;}/*** 將一個集合的所有元素順序添加(追加)到 lits 末尾* - ArrayList 是線程不安全的。* - 該方法沒有加鎖,當一個線程正在將 c 中的元素加入 list 中,但同時有另一個線程在更改 c 中的元素,可能會有問題* @param c  要追加的集合* @return <tt>true</tt> ? list 元素個數有改變時,成功:失敗* @throws NullPointerException 當 c 為 null 時*/public boolean addAll(Collection<? extends E> c) {Object[] a = c.toArray();int numNew = a.length;//要添加元素的個數ensureCapacityInternal(size + numNew);  //擴容System.arraycopy(a, 0, elementData, size, numNew);size += numNew;return numNew != 0;}/*** 從 List 中指定位置開始插入指定集合的所有元素,* -list中原來位置的元素向后移* - 并不會覆蓋掉在 index 位置原有的值* - 類似于 insert 操作,在 index 處插入 c.length 個元素(原來在此處的 n 個元素依次右移)* @param index 插入指定集合的索引* @param c 要添加的集合* @return ? list 元素個數有改變時,成功:失敗* @throws IndexOutOfBoundsException {@inheritDoc}* @throws NullPointerException if the specified collection is null*/public boolean addAll(int index, Collection<? extends E> c) {rangeCheckForAdd(index);Object[] a = c.toArray();//是將list直接轉為Object[] 數組int numNew = a.length;  //要添加集合的元素數量ensureCapacityInternal(size + numNew);  // 擴容int numMoved = size - index;//list中要移動的數量if (numMoved > 0)System.arraycopy(elementData, index, elementData, index + numNew,numMoved);System.arraycopy(a, 0, elementData, index, numNew);size += numNew;return numNew != 0;}/*** 移除list中 [fromIndex,toIndex) 的元素* - 從toIndex之后(包括toIndex)的元素向前移動(toIndex-fromIndex)個元素* -如果(toIndex==fromIndex)這個操作沒有影響* @throws IndexOutOfBoundsException if {@code fromIndex} or*         {@code toIndex} is out of range*         ({@code fromIndex < 0 ||*          fromIndex >= size() ||*          toIndex > size() ||*          toIndex < fromIndex})*/protected void removeRange(int fromIndex, int toIndex) {modCount++;int numMoved = size - toIndex;//要移動的數量System.arraycopy(elementData, toIndex, elementData, fromIndex,numMoved);// 刪除后,list 的長度int newSize = size - (toIndex-fromIndex);//將失效元素置空for (int i = newSize; i < size; i++) {elementData[i] = null;}size = newSize;}/*** 添加時檢查索引是否越界*/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;}/*** 移除list中指定集合包含的所有元素* @param c 要從list中移除的指定集合* @return {@code true} if this list changed as a result of the call* @throws ClassCastException 如果list中的一個元素的類和指定集合不兼容* (<a href="Collection.html#optional-restrictions">optional</a>)* @throws NullPointerException  如果list中包含一個空元素,而指定集合中不允許有空元素*/public boolean removeAll(Collection<?> c) {Objects.requireNonNull(c);//判斷集合是否為空,如果為空報NullPointerException//批量移除c集合的元素,第二個參數:是否采補集return batchRemove(c, false);}/*** Retains only the elements in this list that are contained in the* specified collection.  In other words, removes from this list all* of its elements that are not contained in the specified collection.** @param c collection containing elements to be retained in this list* @return {@code true} if this list changed as a result of the call* @throws ClassCastException if the class of an element of this list*         is incompatible with the specified collection* (<a href="Collection.html#optional-restrictions">optional</a>)* @throws NullPointerException if this list contains a null element and the*         specified collection does not permit null elements* (<a href="Collection.html#optional-restrictions">optional</a>),*         or if the specified collection is null* @see Collection#contains(Object)*/public boolean retainAll(Collection<?> c) {Objects.requireNonNull(c);return batchRemove(c, true);}/*** 批處理移除* @param c 要移除的集合* @param complement 是否是補集*                   如果true:移除list中除了c集合中的所有元素*                   如果false:移除list中 c集合中的元素*/private boolean batchRemove(Collection<?> c, boolean complement) {final Object[] elementData = this.elementData;int r = 0, w = 0;boolean modified = false;try {//遍歷數組,并檢查這個集合是否對應值,移動要保留的值到數組前面,w最后值為要保留的值得數量//如果保留:將相同元素移動到前段,如果不保留:將不同的元素移動到前段for (; r < size; r++)if (c.contains(elementData[r]) == complement)elementData[w++] = elementData[r];} finally {//最后 r=size 注意for循環中最后的r++//     w=保留元素的大小// Preserve behavioral compatibility with AbstractCollection,// even if c.contains() throws.//r!=size表示可能出錯了,if (r != size) {System.arraycopy(elementData, r,elementData, w,size - r);w += size - r;}//如果w==size:表示全部元素都保留了,所以也就沒有刪除操作發生,所以會返回false;反之,返回true,并更改數組//而 w!=size;即使try拋出異常,也能正常處理異常拋出前的操作,因為w始終要為保留的前半部分,數組也不會因此亂序if (w != size) {// clear to let GC do its workfor (int i = w; i < size; i++)elementData[i] = null;modCount += size - w;size = w;modified = true;}}return modified;}/***  私有方法*  將ArrayList實例序列化*/private void writeObject(java.io.ObjectOutputStream s)throws java.io.IOException{// 寫入所有元素數量的任何隱藏的東西int expectedModCount = modCount;s.defaultWriteObject();//寫入clone行為的容量大小s.writeInt(size);//以合適的順序寫入所有的元素for (int i=0; i<size; i++) {s.writeObject(elementData[i]);}if (modCount != expectedModCount) {throw new ConcurrentModificationException();}}/*** 私有方法* 從反序列化中重構ArrayList實例*/private void readObject(java.io.ObjectInputStream s)throws java.io.IOException, ClassNotFoundException {elementData = EMPTY_ELEMENTDATA;//讀出大小和隱藏的東西s.defaultReadObject();// 從輸入流中讀取ArrayList的sizes.readInt(); // ignoredif (size > 0) {ensureCapacityInternal(size);Object[] a = elementData;// 從輸入流中將“所有的元素值”讀出for (int i=0; i<size; i++) {a[i] = s.readObject();}}}/*** 返回從指定索引開始到結束的帶有元素的list迭代器*/public ListIterator<E> listIterator(int index) {if (index < 0 || index > size)throw new IndexOutOfBoundsException("Index: "+index);return new ListItr(index);}/*** 返回從0索引開始到結束的帶有元素的list迭代器*/public ListIterator<E> listIterator() {return new ListItr(0);}/*** 以一種合適的排序返回一個iterator到元素的結尾*/public Iterator<E> iterator() {return new Itr();}/*** Itr是AbstractList.Itr的優化版本* 為什么會報ConcurrentModificationException異常?* 1. Iterator 是工作在一個獨立的線程中,并且擁有一個 mutex 鎖。* 2. Iterator 被創建之后會建立一個指向原來對象的單鏈索引表,當原來的對象數量發生變化時,* 這個索引表的內容不會同步改變,所以當索引指針往后移動的時候就找不到要迭代的對象,* 3. 所以按照 fail-fast 原則 Iterator 會馬上拋出 java.util.ConcurrentModificationException 異常。* 4. 所以 Iterator 在工作的時候是不允許被迭代的對象被改變的。* 但你可以使用 Iterator 本身的方法 remove() 來刪除對象,* 5. Iterator.remove() 方法會在刪除當前迭代對象的同時維護索引的一致性。*/private class Itr implements Iterator<E> {int cursor;       // 下一個元素返回的索引int lastRet = -1; // 最后一個元素返回的索引  -1 if no suchint expectedModCount = modCount;/*** 是否有下一個元素*/public boolean hasNext() {return cursor != size;}/*** 返回list中的值*/@SuppressWarnings("unchecked")public E next() {checkForComodification();int i = cursor;//i當前元素的索引if (i >= size)//第一次檢查:角標是否越界越界throw new NoSuchElementException();Object[] elementData = ArrayList.this.elementData;if (i >= elementData.length)//第二次檢查,list集合中數量是否發生變化throw new ConcurrentModificationException();cursor = i + 1; //cursor 下一個元素的索引return (E) elementData[lastRet = i];//最后一個元素返回的索引}/*** 移除集合中的元素*/public void remove() {if (lastRet < 0)throw new IllegalStateException();checkForComodification();try {//移除list中的元素ArrayList.this.remove(lastRet);//由于cursor比lastRet大1,所有這行代碼是指指針往回移動一位cursor = lastRet;//將最后一個元素返回的索引重置為-1lastRet = -1;//重新設置了expectedModCount的值,避免了ConcurrentModificationException的產生expectedModCount = modCount;} catch (IndexOutOfBoundsException ex) {throw new ConcurrentModificationException();}}/*** jdk 1.8中使用的方法* 將list中的所有元素都給了consumer,可以使用這個方法來取出元素*/@Override@SuppressWarnings("unchecked")public void forEachRemaining(Consumer<? super E> 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++]);}// update once at end of iteration to reduce heap write trafficcursor = i;lastRet = i - 1;checkForComodification();}/*** 檢查modCount是否等于expectedModCount* 在 迭代時list集合的元素數量發生變化時會造成這兩個值不相等*/final void checkForComodification() {//當expectedModCount和modCount不相等時,就拋出ConcurrentModificationExceptionif (modCount != expectedModCount)throw new ConcurrentModificationException();}}/*------------------------------------- Itr 結束 -------------------------------------------*//*** AbstractList.ListItr 的優化版本* ListIterator 與普通的 Iterator 的區別:* - 它可以進行雙向移動,而普通的迭代器只能單向移動* - 它可以添加元素(有 add() 方法),而后者不行*/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;}/*** 獲取 cursor 前一個元素的索引* - 是 cursor 前一個,而不是當前元素前一個的索引。* - 若調用 next() 后馬上調用該方法,則返回的是當前元素的索引。* - 若調用 next() 后想獲取當前元素前一個元素的索引,需要連續調用兩次該方法。*/public int previousIndex() {return cursor - 1;}/*** 返回 cursor 前一元素*/@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;//cursor回移return (E) elementData[lastRet = i];//返回 cursor 前一元素}/*** 將數組的最后一個元素,設置成元素e*/public void set(E e) {if (lastRet < 0)throw new IllegalStateException();checkForComodification();try {//將數組最后一個元素,設置成元素eArrayList.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);//在i位置上添加元素ecursor = i + 1;//cursor后移一位lastRet = -1;expectedModCount = modCount;} catch (IndexOutOfBoundsException ex) {throw new ConcurrentModificationException();}}}/*------------------------------------- ListItr 結束 -------------------------------------------*//*** 獲取從 fromIndex 到 toIndex 之間的子集合(左閉右開區間)* - 若 fromIndex == toIndex,則返回的空集合* - 對該子集合的操作,會影響原有集合* - 當調用了 subList() 后,若對原有集合進行刪除操作(刪除subList 中的首個元素)時,會拋出異常 java.util.ConcurrentModificationException*  這個和Itr的原因差不多由于modCount發生了改變,對集合的操作需要用子集合提供的方法* - 該子集合支持所有的集合操作** 原因看 SubList 內部類的構造函數就可以知道* @throws IndexOutOfBoundsException {@inheritDoc}* @throws IllegalArgumentException {@inheritDoc}*/public List<E> subList(int fromIndex, int toIndex) {subListRangeCheck(fromIndex, toIndex, size);return new SubList(this, 0, fromIndex, toIndex);}/*** 檢查傳入索引的合法性* 注意[fromIndex,toIndex)*/static void subListRangeCheck(int fromIndex, int toIndex, int size) {if (fromIndex < 0)throw new IndexOutOfBoundsException("fromIndex = " + fromIndex);if (toIndex > size)//由于是左閉右開的,所以toIndex可以等于sizethrow new IndexOutOfBoundsException("toIndex = " + toIndex);if (fromIndex > toIndex)throw new IllegalArgumentException("fromIndex(" + fromIndex +") > toIndex(" + toIndex + ")");}/*** 私有類* 嵌套內部類:也實現了 RandomAccess,提供快速隨機訪問特性* 這個是通過映射來實現的*/private class SubList extends AbstractList<E> implements RandomAccess {private final AbstractList<E> parent; //實際傳入的是ArrayList本身private final int parentOffset;  // 相對于父集合的偏移量,其實就是 fromIndexprivate final int offset;  // 偏移量,默認是 0int size;   //SubList中的元素個數SubList(AbstractList<E> parent,int offset, int fromIndex, int toIndex) {// 看到這部分,就理解為什么對 SubList 的操作,會影響父集合---> 因為子集合的處理,僅僅是給出了一個映射到父集合相應區間的引用// 再加上 final,的修飾,就能明白為什么進行了截取子集合操作后,父集合不能刪除 SubList 中的首個元素了--->offset 不能更改this.parent = parent;this.parentOffset = fromIndex;//原來的偏移量this.offset = offset + fromIndex;//加了offset的偏移量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();//從這里可以看出,先通過index拿到在原來數組上的索引,再調用父類的添加方法實現添加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;}/*** 移除subList中的[fromIndex,toIndex)之間的元素*/protected void removeRange(int fromIndex, int toIndex) {checkForComodification();parent.removeRange(parentOffset + fromIndex,parentOffset + toIndex);this.modCount = parent.modCount;this.size -= toIndex - fromIndex;}/*** 添加集合中的元素到subList結尾* @param c* @return*/public boolean addAll(Collection<? extends E> c) {//調用父類的方法添加集合元素return addAll(this.size, c);}/*** 在subList指定位置,添加集合中的元素*/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;}/*** subList中的迭代器*/public Iterator<E> iterator() {return listIterator();}/*** 返回從指定索引開始到結束的帶有元素的list迭代器*/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)];}//jdk8的方法@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 trafficlastRet = 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();}};}//subList的方法,同樣可以再次截取List同樣是使用映射方式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();}/*** subList方法:獲取一個分割器* - fail-fast* - late-binding:后期綁定* - java8 開始提供*/public Spliterator<E> spliterator() {checkForComodification();return new ArrayListSpliterator<E>(ArrayList.this, offset,offset + this.size, this.modCount);}}/*------------------SubList結束-------------------------------*///1.8方法@Overridepublic 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]);//這里將所有元素都接受到Consumer中了,所有可以使用1.8中的方法直接獲取每一個元素}if (modCount != expectedModCount) {throw new ConcurrentModificationException();}}/*** 獲取一個分割器* - fail-fast 機制和itr,subList一個機制* - late-binding:后期綁定* - java8 開始提供* @return a {@code Spliterator} over the elements in this list* @since 1.8*/@Overridepublic Spliterator<E> spliterator() {return new ArrayListSpliterator<>(this, 0, -1, 0);}/** Index-based split-by-two, lazily initialized Spliterator */// 基于索引的、二分的、懶加載的分割器static final class ArrayListSpliterator<E> implements Spliterator<E> {//用于存放ArrayList對象private final ArrayList<E> list;//起始位置(包含),advance/split操作時會修改private int index;//結束位置(不包含),-1 表示到最后一個元素private int fence;//用于存放list的modCountprivate int expectedModCount;//默認的起始位置是0,默認的結束位置是-1ArrayListSpliterator(ArrayList<E> list, int origin, int fence,int expectedModCount) {this.list = list; // OK if null unless traversedthis.index = origin;this.fence = fence;this.expectedModCount = expectedModCount;}//在第一次使用時實例化結束位置private int getFence() {int hi; // (a specialized variant appears in method forEach)ArrayList<E> lst;//fence<0時(第一次初始化時,fence才會小于0):if ((hi = fence) < 0) {//如果list集合中沒有元素if ((lst = list) == null)//list 為 null時,fence=0hi = fence = 0;else {//否則,fence = list的長度。expectedModCount = lst.modCount;hi = fence = lst.size;}}return hi;}//分割list,返回一個新分割出的spliterator實例//相當于二分法,這個方法會遞歸//1.ArrayListSpliterator本質上還是對原list進行操作,只是通過index和fence來控制每次處理范圍//2.也可以得出,ArrayListSpliterator在遍歷元素時,不能對list進行結構變更操作,否則拋錯。public ArrayListSpliterator<E> trySplit() {//hi:結束位置(不包括)  lo:開始位置   mid:中間位置int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;//當lo>=mid,表示不能在分割,返回null//當lo<mid時,可分割,切割(lo,mid)出去,同時更新index=mid/**如:   | 0 | 1 | 2 | 3 | 4 | 5 |    數組長度為6 的進行 split*   結束角標 hi:6    開始角標lo:0    mid:3    lo<mid*   [0,3)  同時 lo:3   hi:6    mid:4*   [3,4)  同時  lo:4   hi:6   mid:5*   [4,5)  同時   lo:5   hid:6   mid:5*   null*/return (lo >= mid) ? null : // divide range in half unless too smallnew ArrayListSpliterator<E>(list, lo, index = mid,expectedModCount);}//返回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);//給Consumer類函數if (list.modCount != expectedModCount)//遍歷時,結構發生變更,拋錯throw new ConcurrentModificationException();return true;}return false;}//順序遍歷處理所有剩下的元素//Consumer類型,傳入值處理public void forEachRemaining(Consumer<? super E> action) {int i, hi, mc; // hi list的長度 )ArrayList<E> lst; Object[] a;//數組,元素集合if (action == null)throw new NullPointerException();//如果list不為空 而且  list中的元素不為空if ((lst = list) != null && (a = lst.elementData) != null) {//當fence<0時,表示fence和expectedModCount未初始化,可以思考一下這里能否直接調用getFence(),嘿嘿?if ((hi = fence) < 0) {mc = lst.modCount;hi = lst.size;//由于上面判斷過了,可以直接將lst大小給hi(不包括)}elsemc = expectedModCount;if ((i = index) >= 0 && (index = hi) <= a.length) {for (; i < hi; ++i) {//將所有元素給Consumer@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);}//打上特征值:、可以返回sizepublic int characteristics() {//命令,大小,子大小return Spliterator.ORDERED | Spliterator.SIZED | Spliterator.SUBSIZED;}}/*** 1.8方法* 根據Predicate條件來移除元素* 將所有元素依次根據filter的條件判斷* Predicate 是 傳入元素 返回 boolean 類型的接口*/@Overridepublic 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 unmodifiedint removeCount = 0;final BitSet removeSet = new BitSet(size);final int expectedModCount = 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)) {//如果元素滿足條件removeSet.set(i);//將滿足條件的角標存放到set中removeCount++;//移除set的數量}}if (modCount != expectedModCount) {//判斷是否外部修改了throw new ConcurrentModificationException();}// shift surviving elements left over the spaces left by removed elementsfinal boolean anyToRemove = removeCount > 0;//如果有移除元素if (anyToRemove) {final int newSize = size - removeCount;//新大小//i:[0,size)   j[0,newSize)for (int i=0, j=0; (i < size) && (j < newSize); i++, j++) {i = removeSet.nextClearBit(i);//i是[0,size)中不是set集合中的角標elementData[j] = elementData[i];//新元素}//將空元素置空for (int k=newSize; k < size; k++) {elementData[k] = null;  // Let gc do its work}this.size = newSize;if (modCount != expectedModCount) {throw new ConcurrentModificationException();}modCount++;}return anyToRemove;}/*** UnaryOperator 接受一個什么類型的參數,返回一個什么類型的參數* 對數組中的每一個元素進行一系列的操作,返回同樣的元素,* 如果 List<Student> lists  將list集合中的每一個student姓名改為張三* 使用這個方法就非常方便* @param operator*/@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++) {//取出每一個元素給operator的apply方法elementData[i] = operator.apply((E) elementData[i]);}if (modCount != expectedModCount) {throw new ConcurrentModificationException();}modCount++;}/*** 根據 Comparator條件進行排序* Comparator(e1,e2) 返回 boolean類型*/@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++;}
}
                            
                        
                        
                        總結
以上是生活随笔為你收集整理的ArrayList源码分析的全部內容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: Visual studio2012密钥
- 下一篇: Winrunner实验三 测试脚本编程
