小葵花妈妈课堂开课了:《ArrayList源码浅析》
生活随笔
收集整理的這篇文章主要介紹了
小葵花妈妈课堂开课了:《ArrayList源码浅析》
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
官方文檔源碼介紹:
/*** Resizable-array implementation of the <tt>List</tt> interface. Implements* all optional list operations, and permits all elements, including* <tt>null</tt>. In addition to implementing the <tt>List</tt> interface,* this class provides methods to manipulate the size of the array that is* used internally to store the list. (This class is roughly equivalent to* <tt>Vector</tt>, except that it is unsynchronized.)** <p>The <tt>size</tt>, <tt>isEmpty</tt>, <tt>get</tt>, <tt>set</tt>,* <tt>iterator</tt>, and <tt>listIterator</tt> operations run in constant* time. The <tt>add</tt> operation runs in <i>amortized constant time</i>,* that is, adding n elements requires O(n) time. All of the other operations* run in linear time (roughly speaking). The constant factor is low compared* to that for the <tt>LinkedList</tt> implementation.** <p>Each <tt>ArrayList</tt> instance has a <i>capacity</i>. The capacity is* the size of the array used to store the elements in the list. It is always* at least as large as the list size. As elements are added to an ArrayList,* its capacity grows automatically. The details of the growth policy are not* specified beyond the fact that adding an element has constant amortized* time cost.** <p>An application can increase the capacity of an <tt>ArrayList</tt> instance* before adding a large number of elements using the <tt>ensureCapacity</tt>* operation. This may reduce the amount of incremental reallocation.** <p><strong>Note that this implementation is not synchronized.</strong>* If multiple threads access an <tt>ArrayList</tt> instance concurrently,* and at least one of the threads modifies the list structurally, it* <i>must</i> be synchronized externally. (A structural modification is* any operation that adds or deletes one or more elements, or explicitly* resizes the backing array; merely setting the value of an element is not* a structural modification.) This is typically accomplished by* synchronizing on some object that naturally encapsulates the list.** If no such object exists, the list should be "wrapped" using the* {@link Collections#synchronizedList Collections.synchronizedList}* method. This is best done at creation time, to prevent accidental* unsynchronized access to the list:<pre>* List list = Collections.synchronizedList(new ArrayList(...));</pre>** <p><a name="fail-fast">* The iterators returned by this class's {@link #iterator() iterator} and* {@link #listIterator(int) listIterator} methods are <em>fail-fast</em>:</a>* if the list is structurally modified at any time after the iterator is* created, in any way except through the iterator's own* {@link ListIterator#remove() remove} or* {@link ListIterator#add(Object) add} methods, the iterator will throw a* {@link ConcurrentModificationException}. Thus, in the face of* concurrent modification, the iterator fails quickly and cleanly, rather* than risking arbitrary, non-deterministic behavior at an undetermined* time in the future.** <p>Note that the fail-fast behavior of an iterator cannot be guaranteed* as it is, generally speaking, impossible to make any hard guarantees in the* presence of unsynchronized concurrent modification. Fail-fast iterators* throw {@code ConcurrentModificationException} on a best-effort basis.* Therefore, it would be wrong to write a program that depended on this* exception for its correctness: <i>the fail-fast behavior of iterators* should be used only to detect bugs.</i>** <p>This class is a member of the* <a href="{@docRoot}openjdk-redirect.html?v=8&path=/technotes/guides/collections/index.html">* Java Collections Framework</a>.** @author Josh Bloch* @author Neal Gafter* @see Collection* @see List* @see LinkedList* @see Vector* @since 1.2*/ /*** Resizable-array實現了List的接口。實現所有列表操作, 并且允許所有元素為null.* 不僅實現了List接口,這個類也提供了操作數組的大小的方法,這些方法通常用來存儲list.* 除了該類是不同步的,那么這個類就相當于Vector。** size,isEmpty,get,set,interator,listIterator都是已固定時間運行。add操作以分攤的固定時間* 運行,也就是添加n各元素,需要O(n)的時間。所有其他操作都已線性時間運行。* 與用于LinkedList實現的常數因子相比,此實現的常數因子較低。** 每一個ArrayList實例都有容量。容量是list中存儲元素的數組的個數。它總是至少和list的大小一樣大。* 作為一個元素添加到ArrayList中,容量自動增長。并未指定增長策略的細節,* 因為這不只是添加元素會帶來分攤固定時間開銷那么簡單。** 在添加大容量元素之前,我們需要使用ensureCapacity操作,提升ArrayList實例的容量。* 這可以減少遞增式再分配的容量。** 需要注意的是,這個實現并不是同步的。如果多線程同時訪問同一個ArrayList實例,并且至少有一個* 線程修改了list的結構,他必須保持外部同步。結構上的修改包括add、delete一個或多個元素,或者調整* 數組的大小;只是設置一個元素的具體值并不是一種結構調整。通常需要一些object做同步,* 來完成自然分裝列表。* 如果沒有object去進行同步的話,那么list就需要使用* Collections.synchronizedList Collections.synchronizedList方法進行封裝。* 這樣可以防止意外的并且沒有進行同步的情況下去獲得list實例。* List list = Collections.synchronizedList(new ArrayList(...));* 可以通過類的iterator()方法獲得迭代器,并且listIterator()方法是快速失效,如果list的結構在iterator* 創建之后的任意時間內被除了自身的 ListIterator#remove()、ListIterator#add(Object)* 方法外修改了,iterator都會拋出一個異常ConcurrentModificationException。* 因此面對并行修改,迭代器很快就會完全失敗,而不是在未來某個不確定的時間發生任意不確定的行為的風險。* 注意,迭代器的fail-fast行為不能得到保證,因為,在沒有同步并發修改的情況下不會獲得任何的硬性保證。* fail-fast迭代器會拋出ConcurrentModificationException異常。因此寫程序時依賴這個異常來保證* 正確性是錯誤的,迭代器的fail-fast行為應該只能用來檢測缺陷。*/ public class ArrayList<E> extends AbstractList<E>implements List<E>, RandomAccess, Cloneable, java.io.Serializable {private static final long serialVersionUID = 8683452581122892189L;/*** Default initial capacity.* 默認容量10*/private static final int DEFAULT_CAPACITY = 10;/*** Shared empty array instance used for empty instances.* 共享空數組實例,被空實例使用。*/private static final Object[] EMPTY_ELEMENTDATA = {};/*** Shared empty array instance used for default sized empty instances. We* distinguish this from EMPTY_ELEMENTDATA to know how much to inflate when* first element is added.* 共享空數組實例用于默認大小的空實例。區別于EMPTY_ELEMENTDATA是,我們知道在添加第一個元素* 的時候需要擴展多少空間。*/private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};/*** 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 == DEFAULTCAPACITY_EMPTY_ELEMENTDATA* will be expanded to DEFAULT_CAPACITY when the first element is added.** ArrayList存儲元素的array buffer。ArrayList的容量即為elementData的大小。* 任何空ArrayList即elementData等于DEFAULTCAPACITY_EMPTY_ELEMENTDATA,* 當第一個元素被添加時,容量將擴充至DEFAULT_CAPACITY*/// Android-note: Also accessed from java.util.Collectionstransient Object[] elementData; // non-private to simplify nested class access/*** The size of the ArrayList (the number of elements it contains).* ArrayList包含的元素個數* @serial*/private int size;/*** Constructs an empty list with the specified initial capacity.* 使用一個指定容量數構建一個空的list** @param initialCapacity the initial capacity of the list* @throws IllegalArgumentException if the specified initial capacity* is negative*/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);}}/*** Constructs an empty list with an initial capacity of ten.* 使用容量10構建一個空的list*/public ArrayList() {this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;}/*** Constructs a list containing the elements of the specified* collection, in the order they are returned by the collection's* iterator.** 使用一個已有的collection構建一個list,并包含已有的所有元素,順序為collection的* 迭代器返回的順序。** @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();if ((size = elementData.length) != 0) {// c.toArray might (incorrectly) not return Object[] (see 6260652)if (elementData.getClass() != Object[].class) {//如果指定的Collection的類型不為Object,將會重新創建一個list,類型為ObjectelementData = Arrays.copyOf(elementData, size, Object[].class);}} else {// replace with empty array.this.elementData = EMPTY_ELEMENTDATA;}}/*** 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.* 把ArrayList的實例修改成為list的當前數量。應用程序可以使用這個操作來減少ArrayList實例的存儲空間。*/public void trimToSize() {modCount++;//如果ArrayList的大小小于elementData的長度,也就是elementData有空余空間//會通過copyOf重新copy一份大小為size的list,達到減少空間的目的if (size < elementData.length) {elementData = (size == 0)? EMPTY_ELEMENTDATA: Arrays.copyOf(elementData, size);}}/*** 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.** 增加ArrayList實例的容量,必要時確保了他可以至少保存minCapacity所指定的元素數量。* @param minCapacity the desired minimum capacity*/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;if (minCapacity > minExpand) {ensureExplicitCapacity(minCapacity);}}private void ensureCapacityInternal(int minCapacity) {if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);}ensureExplicitCapacity(minCapacity);}private void ensureExplicitCapacity(int minCapacity) {modCount++;// overflow-conscious codeif (minCapacity - elementData.length > 0) {//如果需要增長容量grow(minCapacity);}}/*** 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;/*** 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 codeint oldCapacity = elementData.length;// newCapacity = 3/2 oldCapacityint 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) // overflowthrow new OutOfMemoryError();return (minCapacity > MAX_ARRAY_SIZE) ?Integer.MAX_VALUE :MAX_ARRAY_SIZE;}/*** Returns the number of elements in this list.* list中元素的個數** @return the number of elements in this list*/public int size() {return size;}/*** Returns <tt>true</tt> if this list contains no elements.* 如果list中沒有任何元素,則返回true** @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>.** 如果list包含了指定的元素,則返回true。更正式地,當且僅當list包含至少一個元素與指定元素* 相同則返回true。* @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.* 返回第一個與指定元素相等的index,或者如果list中不包含該元素則返回-1.* 換句話說,也就是當查詢到結果會返回index最小的一個,或者查找不到則返回-1.*/public int indexOf(Object o) {if (o == null) {for (int i = 0; i < size; i++) {//找到第一個為null的元素indexif (elementData[i]==null)return i;}} else {for (int i = 0; i < size; i++) {//找到第一個與指定元素相等的非null的 index if (o.equals(elementData[i]))return i;}}//找不到返回-1return -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.* 找到在list最后一個元素與指定元素相等的index,如果找不到則返回-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;}/*** Returns a shallow copy of this <tt>ArrayList</tt> instance. (The* elements themselves are not copied.)** 返回一個ArrayList實例的淺拷貝對象。(元素本身不被復制)** @return a clone of this <tt>ArrayList</tt> instance*/public Object clone() {try {//對elementData進行一次copy,但是所包含的元素沒有改變。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 Cloneablethrow new InternalError(e);}}/*** 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.** 返回一個array,包含了在list中的所有元素,并且順序為從頭到尾。* 返回的array是安全的,也就是說沒有該列表沒有引用返回的arrary。* 換句話說,該方法分配了一個全新的array。* 調用放可以修改返回的數組。** @return an array containing all of the elements in this list in* proper sequence*/public Object[] toArray() {return Arrays.copyOf(elementData, size);}/*** 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.)** 返回一個array包含了list中所有的元素,順序為從頭到尾。返回的array的運行時類型與給定數組* 類型相同。如果list適配于給定的array,則返回該數組。否則,將會按照指定array的運行時類型* 重新分配一個新的array,并且大小為list的大小。** 如果list適配于指定的array后,有多余空間,例如,指定的array比list有更多的元素,那么* 緊接著集合之后的元素會被設置為null。(僅在調用方知道list* 不包含任何空元素的情況下, 可以確定list長度的)*** @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:// 如果大小不匹配,則重新生成一個全新的arrayreturn (T[]) Arrays.copyOf(elementData, size, a.getClass());System.arraycopy(elementData, 0, a, 0, size);// 如果指定的array長度大于lsit的size,將緊鄰著集合之后的元素設置為nullif (a.length > size)a[size] = null;return a;}/*** Returns the element at the specified position in this list.** 返回在list中指定index位置的元素* @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) {if (index >= size)throw new IndexOutOfBoundsException(outOfBoundsMsg(index));return (E) elementData[index];}/*** Replaces the element at the specified position in this list with* the specified element.* 使用指定元素替換指定array中index位置的元素,并返回舊值。** @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) {if (index >= size)throw new IndexOutOfBoundsException(outOfBoundsMsg(index));E oldValue = (E) elementData[index];elementData[index] = element;return oldValue;}/*** 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,確保elementData長度+1,試探性增長elementData長度ensureCapacityInternal(size + 1); // Increments modCount!!elementData[size++] = e;return true;}/*** 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).** 插入一個指定的元素在list的指定pos。并且任意后續的元素將后移動,也就是將其索引+1。** @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) {if (index > size || index < 0)throw new IndexOutOfBoundsException(outOfBoundsMsg(index));ensureCapacityInternal(size + 1); // Increments modCount!!// 將目標index及其以后的元素向后整體移動一個位置,// 也就是插入元素的時候會進行一次copy操作System.arraycopy(elementData, index, elementData, index + 1,size - index);//將目標值寫到指定pos中elementData[index] = element;size++;}/*** Removes the element at the specified position in this list.* Shifts any subsequent elements to the left (subtracts one from their* indices).** 刪除list中指定位置的元素。向左移動后面的所有元素,索引減一。* @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) {if (index >= size)throw new IndexOutOfBoundsException(outOfBoundsMsg(index));modCount++;E oldValue = (E) elementData[index];// 獲取查到需要移動的元素int numMoved = size - index - 1;// 如果需要移動,那么進行一次copy將后面的元素向前copyif (numMoved > 0)System.arraycopy(elementData, index+1, elementData, index,numMoved);//將最后一個賦值為nullelementData[--size] = null; // clear to let GC do its work// 返回刪除位置的元素值return oldValue;}/*** 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 the call).** 如果list中包含指定元素,則移除在list中第一次發現的指定的元素。如果不包含當前元素則不變。* 如果list包含指定的元素則返回true。也就說,如果列表改變了就返回true。** @param o element to be removed from this list, if present* @return <tt>true</tt> if this list contained the specified element*/public boolean remove(Object o) {if (o == null) {for (int index = 0; index < size; index++)// 找到第一個不為null的元素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 remove method that skips bounds checking and does not* return the value removed.* 私有的刪除方法,它會跳過邊界檢查并且不會返回刪除的值。*/private void fastRemove(int index) {modCount++;// 檢測需要移動的元素個數,并進行移動也就是copyint 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}/*** Removes all of the elements from this list. The list will* be empty after this call returns.* 刪除list中所有的元素。當調用之后,list會變為空。*/public void clear() {modCount++;// 將所有元素變為null// clear to let GC do its workfor (int i = 0; i < size; i++)elementData[i] = null;size = 0;}/*** Appends all of the elements in the specified collection to the end of* this list, in the order that they are returned by the* specified collection's Iterator. The behavior of this operation is* undefined if the specified collection is modified while the operation* is in progress. (This implies that the behavior of this call is* undefined if the specified collection is this list, and this* list is nonempty.)** 將指定集合的所有元素添加到list的尾部,順序為給定集合的迭代器返回的順序。* 該操作行為是未定義的,如果指定集合在該操作正在進行的時候被修改了。* 這就意味著,調用行為是未定義的,如果指定集合是list本身,并且list是非空集合。** @param c collection containing elements to be added to this list* @return <tt>true</tt> if this list changed as a result of the call* @throws NullPointerException if the specified collection is null*/public boolean addAll(Collection<? extends E> c) {Object[] a = c.toArray();int numNew = a.length;ensureCapacityInternal(size + numNew); // Increments modCountSystem.arraycopy(a, 0, elementData, size, numNew);size += numNew;return numNew != 0;}/*** Inserts all of the elements in the specified collection into this* list, starting at the specified position. Shifts the element* currently at that position (if any) and any subsequent elements to* the right (increases their indices). The new elements will appear* in the list in the order that they are returned by the* specified collection's iterator.* 將制定的集合的所有元素插入到當前的list中,并在指定位置開始插入。* 移動當前為位置的所有元素并且后續的元素都向右移動。* 在list中的新的元素的順序與給定集合的迭代器返回的順序相同。** @param index index at which to insert the first element from the* specified collection* @param c collection containing elements to be added to this list* @return <tt>true</tt> if this list changed as a result of the call* @throws IndexOutOfBoundsException {@inheritDoc}* @throws NullPointerException if the specified collection is null*/public boolean addAll(int index, Collection<? extends E> c) {if (index > size || index < 0)throw new IndexOutOfBoundsException(outOfBoundsMsg(index));Object[] a = c.toArray();int numNew = a.length;ensureCapacityInternal(size + numNew); // Increments modCountint 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;}/*** Removes from this list all of the elements whose index is between* {@code fromIndex}, inclusive, and {@code toIndex}, exclusive.* Shifts any succeeding elements to the left (reduces their index).* This call shortens the list by {@code (toIndex - fromIndex)} elements.* (If {@code toIndex==fromIndex}, this operation has no effect.)** 刪除指定區間的所有元素,fromIndex<= index < toIndex。* 向左移動所有后續的元素。這將會使list縮減(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) {// Android-changed: Throw an IOOBE if toIndex < fromIndex as documented.// All the other cases (negative indices, or indices greater than the size// will be thrown by System#arrayCopy.if (toIndex < fromIndex) {throw new IndexOutOfBoundsException("toIndex < fromIndex");}modCount++;int numMoved = size - toIndex;System.arraycopy(elementData, toIndex, elementData, fromIndex,numMoved);// clear to let GC do its workint newSize = size - (toIndex-fromIndex);for (int i = newSize; i < size; i++) {elementData[i] = null;}size = newSize;}/*** Constructs an IndexOutOfBoundsException detail message.* Of the many possible refactorings of the error handling code,* this "outlining" performs best with both server and client VMs.*/private String outOfBoundsMsg(int index) {return "Index: "+index+", Size: "+size;}/*** Removes from this list all of its elements that are contained in the* specified collection.** 刪除list中所有包含與指定集合相同的元素。* @param c collection containing elements to be removed from 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 removeAll(Collection<?> c) {Objects.requireNonNull(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.* 只保留list中與指定集合相同的元素。也就是說,移除list所有沒有在指定集合中的元素。** @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);}/*** 批量刪除元素,complement決定是保留還是刪除指定元素。true保留,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];} 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 workfor (int i = w; i < size; i++)elementData[i] = null;modCount += size - w;size = w;modified = true;}}return modified;}/*** Save the state of the <tt>ArrayList</tt> instance to a stream (that* is, serialize it).* 將ArrayList的實例轉態保存為一個流,也就是序列化它。該方法會被反射的方式使用。* 復寫該方法,也就是復寫了序列化的默認方法* @serialData The length of the array backing the <tt>ArrayList</tt>* instance is emitted (int), followed by all of its elements* (each an <tt>Object</tt>) in the proper order.*/private void writeObject(java.io.ObjectOutputStream s)throws java.io.IOException{// Write out element count, and any hidden stuffint 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]);}// 在序列的時候,有線程操作了該list導致結構發生改變,那么將拋出異常。if (modCount != expectedModCount) {throw new ConcurrentModificationException();}// ArrayList的系列化,只是保存了size和elementData}/*** Reconstitute the <tt>ArrayList</tt> instance from a stream (that is,* deserialize it).*/private void readObject(java.io.ObjectInputStream s)throws java.io.IOException, ClassNotFoundException {elementData = EMPTY_ELEMENTDATA;// Read in size, and any hidden stuffs.defaultReadObject();// Read in capacity 讀出sizes.readInt(); // ignoredif (size > 0) {// be like clone(), allocate array based upon size not capacityensureCapacityInternal(size);Object[] a = elementData;// Read in all elements in the proper order.for (int i=0; i<size; i++) {a[i] = s.readObject();}}}/*** Returns a list iterator over the elements in this list (in proper* sequence), starting at the specified position in the list.* The specified index indicates the first element that would be* returned by an initial call to {@link ListIterator#next next}.* An initial call to {@link ListIterator#previous previous} would* return the element with the specified index minus one.** 返回一個list所有元素的迭代器,開始于指定的位置。* 指定的index指示著初次調用next所返回的值。* 初次調用previous會返回指定index-1的值。* <p>The returned list iterator is <a href="#fail-fast"><i>fail-fast</i></a>.** @throws IndexOutOfBoundsException {@inheritDoc}*/public ListIterator<E> listIterator(int index) {if (index < 0 || index > size)throw new IndexOutOfBoundsException("Index: "+index);return new ListItr(index);}/*** Returns a list iterator over the elements in this list (in proper* sequence).* 返回一個包含list所有元素的 list iterator。** <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.** 返回一個包含所有list元素的iterator* <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*/private class Itr implements Iterator<E> {// Android-changed: Add "limit" field to detect end of iteration.// The "limit" of this iterator. This is the size of the list at the time the// iterator was created. Adding & removing elements will invalidate the iteration// anyway (and cause next() to throw) so saving this value will guarantee that the// value of hasNext() remains stable and won't flap between true and false when elements// are added and removed from the list.// Android-changed: 添加了limit字段,用來檢測迭代器結束。limit是在創建iterator// 時list的size。 添加或者刪除元素會引起iteration失效。不管怎樣,保存limit值時要保證hasNext()// 的值保持穩定,并且要保證當list中的元素被添加或者刪除時不會在true or false之間徘徊。protected int limit = ArrayList.this.size;int cursor; // index of next element to return// 指定最后一個已經通過next返回的元素的indexint lastRet = -1; // index of last element returned; -1 if no suchint expectedModCount = modCount;public boolean hasNext() {return cursor < limit;}@SuppressWarnings("unchecked")public E next() {// 如果結構發生變化,會拋出異常if (modCount != expectedModCount)throw new ConcurrentModificationException();int i = cursor;if (i >= limit)throw new NoSuchElementException();Object[] elementData = ArrayList.this.elementData;if (i >= elementData.length)throw new ConcurrentModificationException();cursor = i + 1;return (E) elementData[lastRet = i];}// 移除最后一個已經通過next獲取的元素。public void remove() {if (lastRet < 0)throw new IllegalStateException();if (modCount != expectedModCount)throw new ConcurrentModificationException();try {ArrayList.this.remove(lastRet);cursor = lastRet;lastRet = -1;expectedModCount = modCount;limit--;} catch (IndexOutOfBoundsException ex) {throw new ConcurrentModificationException();}}@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;if (modCount != expectedModCount)throw new ConcurrentModificationException();}}/*** An optimized version of AbstractList.ListItr* ListItr提供了比Itr更多的功能,可以向前遍歷、set、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;}public int previousIndex() {return cursor - 1;}@SuppressWarnings("unchecked")public E previous() {if (modCount != expectedModCount)throw new ConcurrentModificationException();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];}public void set(E e) {if (lastRet < 0)throw new IllegalStateException();if (modCount != expectedModCount)throw new ConcurrentModificationException();try {// 在最后一個已經被遍歷的index處,設置新值ArrayList.this.set(lastRet, e);} catch (IndexOutOfBoundsException ex) {throw new ConcurrentModificationException();}}public void add(E e) {if (modCount != expectedModCount)throw new ConcurrentModificationException();try {int i = cursor;// 在下一個被遍歷的位置,插入一個元素。ArrayList.this.add(i, e);cursor = i + 1;lastRet = -1; // 此操作會重置lastRetexpectedModCount = modCount;limit++;} catch (IndexOutOfBoundsException ex) {throw new ConcurrentModificationException();}}}/*** Returns a view of the portion of this list between the specified* {@code fromIndex}, inclusive, and {@code toIndex}, exclusive. (If* {@code fromIndex} and {@code toIndex} are equal, the returned list is* empty.) The returned list is backed by this list, so non-structural* changes in the returned list are reflected in this list, and vice-versa.* The returned list supports all of the optional list operations.** 返回list在fromIndex<=index<toIndex范圍內的子list。如果fromIndex==toIndex相等* 則返回一個空的list。返回的list是受到當前list支持,返回的list與當前list* 沒有結構上的變化,反之亦然。返回的list支持當前list的所有操作。*** <p>This method eliminates the need for explicit range operations (of* the sort that commonly exist for arrays). Any operation that expects* a list can be used as a range operation by passing a subList view* instead of a whole list. For example, the following idiom* removes a range of elements from a list:* <pre>* list.subList(from, to).clear();* </pre>** 這個方法是清除操作,其需要指定操作范圍。任何操作都期待一個list可以被用來* 作為一個通過傳遞子list視圖來替換整個list的操作范圍。例如下面的代碼,刪除了list中一段范圍* 內的元素。** Similar idioms may be constructed for {@link #indexOf(Object)} and* {@link #lastIndexOf(Object)}, and all of the algorithms in the* {@link Collections} class can be applied to a subList.** 類似的語法可以通過indexOf、lastIndexOf構建,并且在Collections的所有語法都應用到一個* 子list中。** <p>The semantics of the list returned by this method become undefined if* the backing list (i.e., this list) is <i>structurally modified</i> in* any way other than via the returned list. (Structural modifications are* those that change the size of this list, or otherwise perturb it in such* a fashion that iterations in progress may yield incorrect results.)** 如果支持的list,也就是原list通過被返回的list修改了結構那么被返回的list會變成未定義的。* 結構變化也就是,list的大小變化,或者以擾亂iteration方式,使進行中產生錯誤的結果。* @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);}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 + ")");}/*** SubList類似于代理,所有方法都會傳遞到parent去執行。但是可以訪問的大小范圍等都是指定的。* 所有的get\set\remove等方法都是傳遞給parent去執行。*/private class SubList extends AbstractList<E> implements RandomAccess {private final AbstractList<E> parent;private final int parentOffset;private final int offset;int size;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) {if (index < 0 || index >= this.size)throw new IndexOutOfBoundsException(outOfBoundsMsg(index));if (ArrayList.this.modCount != this.modCount)throw new ConcurrentModificationException();E oldValue = (E) ArrayList.this.elementData[offset + index];ArrayList.this.elementData[offset + index] = e;return oldValue;}public E get(int index) {if (index < 0 || index >= this.size)throw new IndexOutOfBoundsException(outOfBoundsMsg(index));if (ArrayList.this.modCount != this.modCount)throw new ConcurrentModificationException();return (E) ArrayList.this.elementData[offset + index];}public int size() {if (ArrayList.this.modCount != this.modCount)throw new ConcurrentModificationException();return this.size;}public void add(int index, E e) {if (index < 0 || index > this.size)throw new IndexOutOfBoundsException(outOfBoundsMsg(index));if (ArrayList.this.modCount != this.modCount)throw new ConcurrentModificationException();parent.add(parentOffset + index, e);this.modCount = parent.modCount;this.size++;}public E remove(int index) {if (index < 0 || index >= this.size)throw new IndexOutOfBoundsException(outOfBoundsMsg(index));if (ArrayList.this.modCount != this.modCount)throw new ConcurrentModificationException();E result = parent.remove(parentOffset + index);this.modCount = parent.modCount;this.size--;return result;}protected void removeRange(int fromIndex, int toIndex) {if (ArrayList.this.modCount != this.modCount)throw new ConcurrentModificationException();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) {if (index < 0 || index > this.size)throw new IndexOutOfBoundsException(outOfBoundsMsg(index));int cSize = c.size();if (cSize==0)return false;if (ArrayList.this.modCount != this.modCount)throw new ConcurrentModificationException();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) {if (ArrayList.this.modCount != this.modCount)throw new ConcurrentModificationException();if (index < 0 || index > this.size)throw new IndexOutOfBoundsException(outOfBoundsMsg(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() {if (expectedModCount != ArrayList.this.modCount)throw new ConcurrentModificationException();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() {if (expectedModCount != ArrayList.this.modCount)throw new ConcurrentModificationException();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 trafficlastRet = cursor = i;if (expectedModCount != ArrayList.this.modCount)throw new ConcurrentModificationException();}public int nextIndex() {return cursor;}public int previousIndex() {return cursor - 1;}public void remove() {if (lastRet < 0)throw new IllegalStateException();if (expectedModCount != ArrayList.this.modCount)throw new ConcurrentModificationException();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();if (expectedModCount != ArrayList.this.modCount)throw new ConcurrentModificationException();try {ArrayList.this.set(offset + lastRet, e);} catch (IndexOutOfBoundsException ex) {throw new ConcurrentModificationException();}}public void add(E e) {if (expectedModCount != ArrayList.this.modCount)throw new ConcurrentModificationException();try {int i = cursor;SubList.this.add(i, e);cursor = i + 1;lastRet = -1;expectedModCount = ArrayList.this.modCount;} catch (IndexOutOfBoundsException ex) {throw new ConcurrentModificationException();}}};}public List<E> subList(int fromIndex, int toIndex) {subListRangeCheck(fromIndex, toIndex, size);return new SubList(this, offset, fromIndex, toIndex);}private String outOfBoundsMsg(int index) {return "Index: "+index+", Size: "+this.size;}public Spliterator<E> spliterator() {if (modCount != ArrayList.this.modCount)throw new ConcurrentModificationException();return new ArrayListSpliterator<E>(ArrayList.this, offset,offset + this.size, this.modCount);}}@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;//forEach的方法內部也是傳統的for循環方式去迭代for (int i=0; modCount == expectedModCount && i < size; i++) {action.accept(elementData[i]);}// Android-note:// Iterator will not throw a CME if we add something while iterating over the *last* element// forEach will throw a CME in this case.if (modCount != expectedModCount) {throw new ConcurrentModificationException();}}/*** Creates a <em><a href="Spliterator.html#binding">late-binding</a></em>* and <em>fail-fast</em> {@link Spliterator} over the elements in this* list.** <p>The {@code Spliterator} reports {@link Spliterator#SIZED},* {@link Spliterator#SUBSIZED}, and {@link Spliterator#ORDERED}.* Overriding implementations should document the reporting of additional* characteristic values.** @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> {/** If ArrayLists were immutable, or structurally immutable (no* adds, removes, etc), we could implement their spliterators* with Arrays.spliterator. Instead we detect as much* interference during traversal as practical without* sacrificing much performance. We rely primarily on* modCounts. These are not guaranteed to detect concurrency* violations, and are sometimes overly conservative about* within-thread interference, but detect enough problems to* be worthwhile in practice. To carry this out, we (1) lazily* initialize fence and expectedModCount until the latest* point that we need to commit to the state we are checking* against; thus improving precision. (This doesn't apply to* SubLists, that create spliterators with current non-lazy* values). (2) We perform only a single* ConcurrentModificationException check at the end of forEach* (the most performance-sensitive method). When using forEach* (as opposed to iterators), we can normally only detect* interference after actions, not before. Further* CME-triggering checks apply to all other possible* violations of assumptions for example null or too-small* elementData array given its size(), that could only have* occurred due to interference. This allows the inner loop* of forEach to run without any further checks, and* simplifies lambda-resolution. While this does entail a* number of checks, note that in the common case of* list.stream().forEach(a), no checks or other computation* occur anywhere other than inside forEach itself. The other* less-often-used methods cannot take advantage of most of* these streamlinings.*/// 如果ArrayList是不變的,或者結構不變(沒有添加、刪除等)。我們就可以// 用Arrays.spliterator實現spliterator。相反,我們在遍歷過程中檢測到盡可能多的沖突,// 而不犧牲大量的性能。我們主要依靠這個字段modCounts。這些不能保證檢測并發沖突。// 在線程干擾中有時過于保守,但是在實踐過程中發現足夠多的問題是值得的。// 貫徹執行,我們是懶加載fence和expectedModCount,直到我們需要使用該值的時候才去初始化// ,從而提高精度。當創建具有當前非惰性的值的spliterators,這不能用于SubLists。// 我們僅在forEach結束時進行一次ConcurrentModificationException檢測(性能上最敏感的方法)。// 當時用forEach時(與iterators相反時),我們通常僅在動作之后檢測沖突,而不是之前。// 繼續CME-triggering檢測,適應于所有其他可能違反的假設,例如null或者給定的array的// 元素大小太小,這些僅能因為沖突而發生。允許forEach的內在循環,在沒有任何進一步檢測的// 的情況下運行,并且lambda-resolution檢測也簡化了。雖然這需要一些檢查,注意// list.stream().forEach(a)一般情況下,不檢測或者除內部之外的任何地方的計算都不檢測。// 其他較少使用的方法并不能充分利用這些方式。// ArrayListSpliterator是java8才提供的。用來可以把ArrayList進行并行處理。// 后面單獨介紹Spliteratorprivate final ArrayList<E> list;private int index; // current index, modified on advance/splitprivate int fence; // -1 until used; then one past last indexprivate 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 traversedthis.index = origin;this.fence = fence;this.expectedModCount = expectedModCount;}private int getFence() { // initialize fence to size on first useint hi; // (a specialized variant appears in method forEach)ArrayList<E> lst;if ((hi = fence) < 0) {if ((lst = list) == null)hi = fence = 0;else {expectedModCount = lst.modCount;hi = fence = lst.size;}}return hi;}// 嘗試去分裂,當前辦法為折中分裂。public ArrayListSpliterator<E> trySplit() {int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;return (lo >= mid) ? null : // divide range in half unless too smallnew ArrayListSpliterator<E>(list, lo, index = mid,expectedModCount);}// 嘗試獲取當前遍歷的值,true為查找到結果的返回值。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 loopArrayList<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;}elsemc = 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();}// 獲取剩余沒有遍歷的sizepublic long estimateSize() {return (long) (getFence() - index);}public int characteristics() {return Spliterator.ORDERED | Spliterator.SIZED | Spliterator.SUBSIZED;}}// 通過filter.test找出哪些元素需要被刪除。@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)) {// 如果element元素需要刪除,則將index對應的removeSet的index位置設置true。removeSet.set(i);removeCount++;}}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;for (int i=0, j=0; (i < size) && (j < newSize); i++, j++) {// 找到最近一個為false的元素,也就是沒有被刪除的元素。i = removeSet.nextClearBit(i);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;}// 遍歷所有元素,通過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++) {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++;} }大概齊完成了,后面會進行性能的比對。及ArrayListSpliterator的使用。
ArrayList性能還是比較快的,存儲了5000個元素花費時間6ms。
總結
以上是生活随笔為你收集整理的小葵花妈妈课堂开课了:《ArrayList源码浅析》的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 调用百度地图进行路线规划
- 下一篇: 学妹跑过来问我为啥Xshell 打不开了