ArrayList源碼分析html
package java.util; import java.util.function.Consumer; import java.util.function.Predicate; import java.util.function.UnaryOperator; import sun.misc.SharedSecrets; 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; /** * 空數組 */ private static final Object[] EMPTY_ELEMENTDATA = {}; /** * 空數組 */ private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {}; /** * 存放元素的數組 */ transient Object[] elementData; /** * 數組的元素個數 */ private int size; /** *有參構造容量大於0,一個新的對應容量的數組賦值給elementData;容量等於0,把空數組賦值給elementData;容**量小於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); } } /** *無參構造:將空數組賦值給了elementData */ public ArrayList() { this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA; } /** *把Collection構建成ArrayList */ public ArrayList(Collection<? extends E> c) { //使用Collection的toArray()方法獲得一個對象數組並賦值給elementData elementData = c.toArray(); //size是容器元素個數,因此集合轉ArrayList存儲時候要對size進行賦值。 if ((size = elementData.length) != 0) { // //這裏是當c.toArray出錯,沒有返回Object[]時,利用Arrays.copyOf 來複制集合c中的元素到elementData數組中 if (elementData.getClass() != Object[].class) elementData = Arrays.copyOf(elementData, size, Object[].class); } else { //假如collection爲空的話,直接給elementData一個空數組 this.elementData = EMPTY_ELEMENTDATA; } } /** * 截斷多餘的容量,在內存緊缺時候使用。 */ public void trimToSize() { modCount++; if (size < elementData.length) { elementData = (size == 0) ? EMPTY_ELEMENTDATA : Arrays.copyOf(elementData, size); } } /** * 分配的數組最大限度。超出可能會OutOfMemoryError */ private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8; /** * 返回元素個數 */ public int size() { return size; } /** * 判斷ArrayList是否爲空 */ public boolean isEmpty() { return size == 0; } /** * 判斷ArrayList是否包含o */ public boolean contains(Object o) { return indexOf(o) >= 0; } /** * 若是容器中的元素有和o相等的,那麼返回第一個相等元素的下標,若是沒有返回-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; } /** * 功能和上面同樣 * 只不過從後尋找 */ 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; } /** * ArrayList的淺拷貝 */ 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); } } /** * ArrayList轉換爲數組 */ public Object[] toArray() { return Arrays.copyOf(elementData, size); } /** * ArrayList轉換爲指定格式的數組 * 若是ArrayList的長度大於數組a的長度,那麼建立一個a類型的新數組 * 若是ArrayList的長度小於數組a的長度,那麼直接把ArrayList元素複製給a,並把下標等於size元素 * 替換爲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: return (T[]) Arrays.copyOf(elementData, size, a.getClass()); System.arraycopy(elementData, 0, a, 0, size); if (a.length > size) a[size] = null; return a; } /** * 查詢 index角標元素 */ public E get(int index) { //越界檢查 rangeCheck(index); return elementData(index); } /** * 更新index角標元素 */ public E set(int index, E element) { //越界檢查 rangeCheck(index); E oldValue = elementData(index); elementData[index] = element; return oldValue; } /** * 從尾部插入元素操做 */ public boolean add(E e) { ensureCapacityInternal(size + 1); // Increments modCount!! //在新數組末端添加一個元素 elementData[size++] = e; return true; } private void ensureCapacityInternal(int minCapacity) { ensureExplicitCapacity(calculateCapacity(elementData, minCapacity)); } private static int calculateCapacity(Object[] elementData, int minCapacity) { //假如ArrayList是經過無參構造方法建立出來的對象,若是大於10就返回元素個數,若是小於10(默認初始容量) //就返回10 if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) { return Math.max(DEFAULT_CAPACITY, minCapacity); } //若是ArrayList不是經過無參構造建立出來的,那麼直接返回元素個數便可 return minCapacity; } //modCount自增,若是須要擴容就進行擴容 private void ensureExplicitCapacity(int minCapacity) { modCount++; //繼承自AbstractList 用來計集合修改的次數 // overflow-conscious code if (minCapacity - elementData.length > 0) grow(minCapacity); } /** * 擴容1.5倍,假如還不夠的話,把元素個數做爲容量。 */ private void grow(int minCapacity) { // overflow-conscious code int oldCapacity = elementData.length; int newCapacity = oldCapacity + (oldCapacity >> 1); if (newCapacity - minCapacity < 0) newCapacity = minCapacity; //若是新容量太大且超過數組最大值,若是元素個數大於數組容量最大值,那麼把容量設爲Integer的最大值 //若是元素個數小於數組最大值,那麼把容量擴容到數組容量最大值便可 if (newCapacity - MAX_ARRAY_SIZE > 0) newCapacity = hugeCapacity(minCapacity); // 構建新數組 elementData = Arrays.copyOf(elementData, newCapacity); } private static int hugeCapacity(int minCapacity) { if (minCapacity < 0) // overflow throw new OutOfMemoryError(); return (minCapacity > MAX_ARRAY_SIZE) ? Integer.MAX_VALUE : MAX_ARRAY_SIZE; } /** * 指定下標插入元素 */ public void add(int index, E element) { //下標越界判斷 rangeCheckForAdd(index); //和尾部增長同樣,判斷是否須要擴容,如需則構建新數組,modCount自增 ensureCapacityInternal(size + 1); // Increments modCount!! //其餘元素下標後移 System.arraycopy(elementData, index, elementData, index + 1, size - index); //把元素添加到index下標處 elementData[index] = element; //元素個數+1 size++; } /** * 判斷index是否越界 */ private void rangeCheckForAdd(int index) { if (index > size || index < 0) throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); } /** * ArrayList尾部添加Collection */ public boolean addAll(Collection<? extends E> c) { //把Collection構建成數組 Object[] a = c.toArray(); int numNew = a.length; //判斷是否須要擴容,如需則構建新數組,modCount自增 ensureCapacityInternal(size + numNew); // Increments modCount //把數組拷貝到原ArrayList尾部 System.arraycopy(a, 0, elementData, size, numNew); //新size size += numNew; return numNew != 0; } /** * 從下標index處插入集合c */ 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; //index處的元素後移數組c長度個位置 if (numMoved > 0) System.arraycopy(elementData, index, elementData, index + numNew, numMoved); //把c數組插入上面移出的空位 System.arraycopy(a, 0, elementData, index, numNew); size += numNew; return numNew != 0; } /** * 若有必要,增長此 ArrayList 實例的容量,以確保它至少可以容納最小容量參數所指定的元素數。 */ public void ensureCapacity(int minCapacity) { //ArrayList不是經過無參構造建立的設置minExpand爲0,若是是經過無參構造建立的設置爲初始容量10 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) { //modCound自增,進行擴容 ensureExplicitCapacity(minCapacity); } } /** * 刪除對應下標的元素 */ public E remove(int index) { //判斷下標是否越界 rangeCheck(index); //modCound自增 modCount++; //根據下標獲取對應的元素 E oldValue = elementData(index); int numMoved = size - index - 1; //假如index對應元素不是最後一個元素,把這個元素後面的其餘元素前移一位 if (numMoved > 0) System.arraycopy(elementData, index+1, elementData, index, numMoved); //把最後一位設置爲默認的null元素 elementData[--size] = null; // clear to let GC do its work //返回移出的元素 return oldValue; } //根據下標獲取數組對應的元素 @SuppressWarnings("unchecked") E elementData(int index) { return (E) elementData[index]; } /** * 若是ArrayList中有o元素,從ArrayList中刪除第一個o元素 */ public boolean remove(Object o) { //循環數組,若是其中元素和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; } /* * modCound自增,移出index處的元素,而後後面元素前移,尾元素賦值null * 不用返回對應元素,不會越界因此不須要越界判斷。 */ 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 } /** * 從ArrayList中刪除Collection包含的元素 */ public boolean removeAll(Collection<?> c) { //查看Objects源碼 此處若是c爲空,拋出空指針異常 Objects.requireNonNull(c); return batchRemove(c, false); } /** * 從ArrayList中保留c中包含的元素 */ public boolean retainAll(Collection<?> c) { Objects.requireNonNull(c); return batchRemove(c, true); } 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++) //complement爲false,c中不包含的元素,從下標爲0處放入到elementData中 //complement爲true,c中包含的元素,從下標爲0處放入到elementData中 if (c.contains(elementData[r]) == complement) elementData[w++] = elementData[r]; } finally { //因爲c.contains報異常致使r!=size,把從r開始的後面項,都賦值到elementData的w項後 //即如今的elementData的w項前的元素,都是c中不包含的。w和w項後的元素還未判斷,總體拿過來 if (r != size) { System.arraycopy(elementData, r, elementData, w, size - r); //把w變爲elementData元素的"size"。這裏的size不是實際的元素個數 //因爲上面爲了提升性能,沒有建立新數組。而是把不被c包含的元素從開頭再次存入這個數組。 //沒有存放過的下標位上不是null而是之前的元素。 w += size - r; } //若是w=size,那麼說明異常前,elementData的前r項都不被c包含 //此處說明有元素不被c包含 //清空上面提到的老元素 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個元素 modCount += size - w; size = w; modified = true; } } return modified; } /** * 清空數組中的元素 */ public void clear() { modCount++; // clear to let GC do its work for (int i = 0; i < size; i++) elementData[i] = null; size = 0; } /** * 刪除從fromIndex到toIndex(不包含)的元素 注意:繼承ArrayList的類纔可用 */ protected void removeRange(int fromIndex, int toIndex) { modCount++; int numMoved = size - toIndex; //把從toInDex開始的元素,複製到fromIndex---fromIndex+numMoed(不包含)處 System.arraycopy(elementData, toIndex, elementData, fromIndex, numMoved); //清空fromIndex+numMoed及後面的元素 // clear to let GC do its work int newSize = size - (toIndex-fromIndex); for (int i = newSize; i < size; i++) { elementData[i] = null; } size = newSize; } /** * 越界檢查 */ private void rangeCheck(int index) { if (index >= size) throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); } private String outOfBoundsMsg(int index) { return "Index: "+index+", Size: "+size; } /** * Save the state of the <tt>ArrayList</tt> instance to a stream (that * is, serialize it). * * @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 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(); } } /** * 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 stuff s.defaultReadObject(); // Read in capacity s.readInt(); // ignored if (size > 0) { // be like clone(), allocate array based upon size not capacity int capacity = calculateCapacity(elementData, size); SharedSecrets.getJavaOISAccess().checkArray(s, Object[].class, 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,Set的時候,爲了實現對其數據的遍歷,咱們常常使用到了Iterator(迭代器)。使用迭代器,你不須要干涉其遍歷的過程,只須要每次取出一個你想要的數據進行處理就能夠了。可是在使用的時候也是有不一樣的。List和Set都有iterator()來取得其迭代器。對List來講,你也能夠經過listIterator()取得其迭代器,兩種迭代器在有些時候是不能通用的, terator和ListIterator主要區別在如下方面: 1. iterator()方法在set和list接口中都有定義,可是ListIterator()僅存在於list接口中(或實現類中); 2. ListIterator有add()方法,能夠向List中添加對象,而Iterator不能 3.ListIterator和Iterator都有hasNext()和next()方法,能夠實現順序向後遍歷,可是ListIterator有hasPrevious()和previous()方法,能夠實現逆向(順序向前)遍歷。Iterator就不能夠。 4. ListIterator能夠定位當前的索引位置,nextIndex()和previousIndex()能夠實現。Iterator沒有此功能。 5.均可實現刪除對象,可是ListIterator能夠實現對象的修改,set()方法能夠實現。Iierator僅能遍歷,不能修改。 由於ListIterator的這些功能,能夠實現對LinkedList等List數據結構的操做。其實,數組對象也能夠用迭代器來實現。 */ /** * 從AbstractList繼承過來的,返回當前索引位置的迭代器 */ public ListIterator<E> listIterator(int index) { if (index < 0 || index > size) throw new IndexOutOfBoundsException("Index: "+index); return new ListItr(index); } /** * 從AbstractList繼承過來的,返回此列表元素的列表迭代器 */ public ListIterator<E> listIterator() { return new ListItr(0); } /** * 返回以恰當順序在此列表的元素上進行迭代的迭代器。 */ public Iterator<E> iterator() { return new Itr(); } /** * An optimized version of AbstractList.Itr */ private class Itr implements Iterator<E> { int cursor; // index of next element to return int lastRet = -1; // index of last element returned; -1 if no such int expectedModCount = modCount; Itr() {} public boolean hasNext() { return cursor != size; } @SuppressWarnings("unchecked") public E next() { checkForComodification(); int i = cursor; if (i >= size) throw new NoSuchElementException(); Object[] elementData = ArrayList.this.elementData; if (i >= elementData.length) throw new ConcurrentModificationException(); cursor = i + 1; return (E) elementData[lastRet = i]; } public void remove() { if (lastRet < 0) throw new IllegalStateException(); checkForComodification(); try { ArrayList.this.remove(lastRet); cursor = lastRet; lastRet = -1; expectedModCount = modCount; } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } } @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 traffic cursor = i; lastRet = i - 1; checkForComodification(); } final void checkForComodification() { if (modCount != expectedModCount) throw new ConcurrentModificationException(); } } /** * An optimized version of 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]; } 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(); } } } /** * 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. * * <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> * 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. * * <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.) * * @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 + ")"); } 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) { 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); } } @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(); } } /** * 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 */ @Override public 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. */ 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() { // initialize fence to size on first use int 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 small new ArrayListSpliterator<E>(list, lo, index = mid, expectedModCount); } 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); } 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); 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); 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 = 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; } @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++; } }
總結 :java
1.底層爲數組,當容量滿時候進行擴容每次爲1.5倍,若是還不夠的話容量爲元素個數。構建新數組,把原數組拷貝進新數組。算法
2.無參建立出來的ArrayList在第一次add時候會給一個10的容量。因此咱們儘量的在建立時候給它一個初始值,若是不肯定那麼用默認的10.數組
3. 查詢效率高,插入刪除元素會致使後面的全部元素前移或者後移下表,致使性能降低。即插入和刪除效率低。數據結構
4.在removeAll和retainAll方法中用到了私有方法batchRemove。這個方法裏面有個個算法,過濾數組中的元素,賦值給原數組。把可能c.contains報異常處理放在了finally中app
LinkedListless