整个ArrayList源码文件
public class ArrayListextends AbstractList implements List , 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; // non-private to simplify nested class access private int size; //size是数组个数 elementData.length是数组容量 public ArrayList(int initialCapacity) { if (initialCapacity > 0) { this.elementData = new Object[initialCapacity]; //如果传入的参数大于0,创建initialCapacity大小的数组 } else if (initialCapacity == 0) { this.elementData = EMPTY_ELEMENTDATA; //如果传入的参数等于0,创建空数组 } else { throw new IllegalArgumentException("Illegal Capacity: "+ initialCapacity); //其他情况,抛出异常 } } public ArrayList() { this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA; } public ArrayList(Collection extends E> c) { Object[] a = c.toArray(); //将指定集合转换为Object数组 if ((size = a.length) != 0) { //如果elementData数组的长度不为0 if (c.getClass() == ArrayList.class) { // 如果指定集合是ArrayList就直接赋值给elementData数组 elementData = a; } else { elementData = Arrays.copyOf(a, size, Object[].class);//将原来不是Object类型的elementData数组的内容,赋值给新的Object类型的elementData数组 } } else { // replace with empty array. // 其他情况,用空数组代替 elementData = EMPTY_ELEMENTDATA; } } public void trimToSize() { modCount++; if (size < elementData.length) { elementData = (size == 0) ? EMPTY_ELEMENTDATA : Arrays.copyOf(elementData, size); } } public void ensureCapacity(int minCapacity) { int minExpand = (elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA) // any size if not default element table ? 0 //判断是不是空的ArrayList,如果是的最小扩充容量10,否则最小扩充量为0 // larger than default for default empty table. It's already // supposed to be at default size. : DEFAULT_CAPACITY; // 若用户指定的最小容量 > 最小扩充容量,则以用户指定的为准,否则还是 10 if (minCapacity > minExpand) { ensureExplicitCapacity(minCapacity); } } // 若 elementData == {},则取 minCapacity 为 默认容量和参数 minCapacity 之间的最大值 默认容量是10 private static int calculateCapacity(Object[] elementData, int minCapacity) { if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) { return Math.max(DEFAULT_CAPACITY, minCapacity); // 获取“默认的容量”和“传入参数”两者之间的最大值 } return minCapacity; } //得到最小扩容量 private void ensureCapacityInternal(int minCapacity) { ensureExplicitCapacity(calculateCapacity(elementData, minCapacity)); } //判断是否需要扩容 private void ensureExplicitCapacity(int minCapacity) { modCount++; // overflow-conscious code // 防止溢出代码:确保指定的最小容量 > 数组缓冲区当前的长度 if (minCapacity - elementData.length > 0) //指定的最小容量比当前数组大就扩容 grow(minCapacity);//调用grow方法进行扩容,调用此方法代表已经开始扩容了 } private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8; private void grow(int minCapacity) { // overflow-conscious code int oldCapacity = elementData.length; // oldCapacity为旧容量,newCapacity为新容量 int newCapacity = oldCapacity + (oldCapacity >> 1); //newCapacity为oldCapacity的1.5倍 >>1是右移一位除以2 if (newCapacity - minCapacity < 0) //然后检查新容量是否小于最小需要容量,若还是小于最小需要容量,那么就把最小需要容量当作数组的新容量,例如数组为空的时候新容量为5 最小容量为10 这时新容量为10 newCapacity = minCapacity; if (newCapacity - MAX_ARRAY_SIZE > 0) //再检查新容量是否超出了ArrayList所定义的最大容量 newCapacity = hugeCapacity(minCapacity);//若超出了,则调用hugeCapacity()来比较minCapacity和 MAX_ARRAY_SIZE // minCapacity is usually close to size, so this is a win://如果minCapacity大于MAX_ARRAY_SIZE,则新容量则为Interger.MAX_VALUE,否则,新容量大小则为 MAX_ARRAY_SIZE。 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 int size() { return size; } public boolean isEmpty() { return size == 0; } public boolean contains(Object o) { return indexOf(o) >= 0; //indexOf()方法:返回此列表中指定元素的首次出现的索引,如果此列表不包含此元素,则为-1 } public int indexOf(Object o) { if (o == null) { for (int i = 0; i < size; i++) if (elementData[i]==null)//指定元素为null就找第一个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; } public Object clone() { try { ArrayList> v = (ArrayList>) super.clone(); v.elementData = Arrays.copyOf(elementData, size);//Arrays.copyOf功能是实现数组的复制,返回复制后的数组。参数是被复制的数组和复制的长度 v.modCount = 0; return v; } catch (CloneNotSupportedException e) { // this shouldn't happen, since we are Cloneable // 这不应该发生,因为我们是可以克隆的 throw new InternalError(e); } } public Object[] toArray() { return Arrays.copyOf(elementData, size); } @SuppressWarnings("unchecked") public T[] toArray(T[] a) { if (a.length < size) // 若数组a的大小 < ArrayList的元素个数,则新建一个T[]数组 // 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);// 若数组a的大小 >= ArrayList的元素个数,则将ArrayList的全部元素都拷贝到数组a中。 if (a.length > size) a[size] = null; return a; } // Positional Access Operations @SuppressWarnings("unchecked") E elementData(int index) { return (E) elementData[index]; } public E get(int index) { rangeCheck(index); return elementData(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); // 元素个数加1 elementData[size++] = e; //保证要存多少个元素,就只分配多少空间资源 这里看到ArrayList添加元素的实质就相当于为数组赋值 先赋值 size再加1 return true; } public void add(int index, E element) { rangeCheckForAdd(index); //第二个是从要复制的数组的第几个开始,第四个是复制到的数组第几个开始,最后一个是复制长度 ensureCapacityInternal(size + 1); // Increments modCount!! System.arraycopy(elementData, index, elementData, index + 1, size - index);//从index开始的元素都右移一位(包括index) elementData[index] = element; size++; } public E remove(int index) { rangeCheck(index); modCount++; E oldValue = elementData(index);//要移除的值 int numMoved = size - index - 1;//要移动的长度 -1是因为不包括index if (numMoved > 0) System.arraycopy(elementData, index+1, elementData, index, numMoved); elementData[--size] = null; // clear to let GC do its work 将最后一个元素置空 return oldValue; } public boolean remove(Object o) { if (o == null) { for (int index = 0; index < size; index++) if (elementData[index] == null) { fastRemove(index); return true; } } else { for (int index = 0; index < size; index++) if (o.equals(elementData[index])) { fastRemove(index); return true; } } return false; } private void fastRemove(int index) { modCount++; 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 } public void clear() { modCount++; // clear to let GC do its work for (int i = 0; i < size; i++) elementData[i] = null; size = 0; } public boolean addAll(Collection extends E> c) { Object[] a = c.toArray(); int numNew = a.length;//要添加元素的个数 ensureCapacityInternal(size + numNew); // Increments modCount,看要不要扩容 System.arraycopy(a, 0, elementData, size, numNew);//把集合c复制到list里 size += numNew; return numNew != 0; } 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;//原来list中要移动的数量 if (numMoved > 0)//从index开始后面的元素右移 0 1 4 5 6 从4添加 2 3,4 5 6右移两位 变成 0 1 _ _ 4 5 6 System.arraycopy(elementData, index, elementData, index + numNew, numMoved); //把指定集合的元素复制到list System.arraycopy(a, 0, elementData, index, numNew); size += numNew; return numNew != 0; } protected void removeRange(int fromIndex, int toIndex) { modCount++; int numMoved = size - toIndex; //要移动的数量 0 1 2 3 4 from是1 to是3 numMoved = 5 - 3 = 2 3左移2位 变成0 3 4 3 4 System.arraycopy(elementData, toIndex, elementData, fromIndex, numMoved); // clear to let GC do its work int newSize = size - (toIndex-fromIndex); for (int i = newSize; i < size; i++) { elementData[i] = null; // 把后面元素置空 0 3 4 3 4 变成 0 3 4 } size = newSize; } private void rangeCheck(int index) { if (index >= size) throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); } private void rangeCheckForAdd(int index) { if (index > size || index < 0) throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); } private String outOfBoundsMsg(int index) { return "Index: "+index+", Size: "+size; } public boolean removeAll(Collection> c) { Objects.requireNonNull(c);//判断集合是否为空,如果为空报NullPointerException return batchRemove(c, false);//批量移除c集合的元素,第二个参数:是否采补集 } 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 { for (; r < size; r++) //补集的话就移除c以外的元素,保留c 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 work for (int i = w; i < size; i++) elementData[i] = null; modCount += size - w; size = w; modified = true; } } return modified; } private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException{ // Write out element count, and any hidden stuff // 写入所有元素数量的任何隐藏的东西 int expectedModCount = modCount; s.defaultWriteObject(); // Write out size as capacity for behavioural compatibility with clone() s.writeInt(size);//写入clone行为的容量大小 // Write out all elements in the proper order. for (int i=0; i 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 listIterator(int index) { if (index < 0 || index > size) throw new IndexOutOfBoundsException("Index: "+index); return new ListItr(index); } public ListIterator listIterator() { return new ListItr(0); } public Iterator iterator() { return new Itr(); } private class Itr implements Iterator { int cursor; // index of next element to return // 下一个元素返回的索引 int lastRet = -1; // index of last element returned; -1 if no such // 最后一个元素返回的索引 -1 if no such int expectedModCount = modCount; Itr() {} //Iterator 被创建之后会建立一个指向原来对象的单链索引表,当原来的对象数量发生变化时, // 这个索引表的内容不会同步改变,所以当索引指针往后移动的时候就找不到要迭代的对象,然后抛出ConcurrentModificationException 异常 public boolean hasNext() { //所以 Iterator 在工作的时候是不允许被迭代的对象被改变的。但你可以使用 Iterator 本身的方法 remove() 来删除对象, return cursor != size; //Iterator.remove() 方法会在删除当前迭代对象的同时维护索引的一致性。 } @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 { ArrayList.this.remove(lastRet);//移除list中的元素 cursor = lastRet; //由于cursor比lastRet大1,所有这行代码是指指针往左移动一位 lastRet = -1;//将最后一个元素返回的索引重置为-1 expectedModCount = modCount;//重新设置了expectedModCount的值,避免了ConcurrentModificationException的产生 } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } } //将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 traffic cursor = i; lastRet = i - 1; checkForComodification(); } //检查modCount是否等于expectedModCount 在迭代时list集合的元素数量发生变化时会造成这两个值不相等 final void checkForComodification() { if (modCount != expectedModCount) //当expectedModCount和modCount不相等时,就抛出ConcurrentModificationException throw new ConcurrentModificationException(); } } //和普通的 Iterator 的区别,可以双向移动,可以添加元素 private class ListItr extends Itr implements ListIterator { ListItr(int index) { super(); cursor = index; } //是否有前一个元素 public boolean hasPrevious() { return cursor != 0; } public int nextIndex() { return cursor; } //获取 cursor 前一个元素的索引 public int previousIndex() { //是 cursor 前一个,而不是当前元素前一个的索引。 return cursor - 1; //若调用 next() 后马上调用该方法,则返回的是当前元素的索引。 } //若调用 next() 后想获取当前元素前一个元素的索引,需要连续调用两次该方法。 //返回 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 { 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); //在i位置上添加元素e cursor = i + 1;//cursor后移一位 lastRet = -1; expectedModCount = modCount; } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } } } public List 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) //由于是左闭右开的,所以toIndex可以等于size throw new IndexOutOfBoundsException("toIndex = " + toIndex); if (fromIndex > toIndex) throw new IllegalArgumentException("fromIndex(" + fromIndex + ") > toIndex(" + toIndex + ")"); } //嵌套内部类:也实现了 RandomAccess,提供快速随机访问特性 这个是通过映射来实现的 private class SubList extends AbstractList implements RandomAccess { private final AbstractList parent; //实际传入的是ArrayList本身 private final int parentOffset; // 相对于父集合的偏移量,其实就是 fromIndex private final int offset; // 偏移量,默认是 0 int size; //SubList中的元素个数 SubList(AbstractList parent, int offset, int fromIndex, int toIndex) { 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); //从这里可以看出,先通过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; } // 移除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结尾 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 iterator() { return listIterator(); } // 返回从指定索引开始到结束的带有元素的list迭代器 public ListIterator listIterator(final int index) { checkForComodification(); rangeCheckForAdd(index); final int offset = this.offset; return new ListIterator () { 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(); } }; } // 再次截取subList public List 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 spliterator() { checkForComodification(); return new ArrayListSpliterator (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]); //这里将所有元素都接受到Consumer中了,所有可以使用1.8中的方法直接获取每一个元素 } if (modCount != expectedModCount) { throw new ConcurrentModificationException(); } } @Override public Spliterator spliterator() { return new ArrayListSpliterator<>(this, 0, -1, 0); } // 基于索引的、二分的、懒加载的分割器 static final class ArrayListSpliterator implements Spliterator { private final ArrayList list; //用于存放ArrayList对象 private int index; // current index, modified on advance/split /起始位置(包含),advance/split操作时会修改 private int fence; // -1 until used; then one past last index //结束位置(不包含),-1 表示到最后一个元素 private int expectedModCount; // initialized when fence set //用于存放list的modCount //默认的起始位置是0,默认的结束位置是-1 ArrayListSpliterator(ArrayList 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 lst; if ((hi = fence) < 0) { //fence<0时(第一次初始化时,fence才会小于0): if ((lst = list) == null) hi = fence = 0; //list 为 null时,fence=0 else { expectedModCount = lst.modCount; hi = fence = lst.size; //否则,fence = list的长度。 0 1 fence为2 } } return hi; } //分割list,返回一个新分割出的spliterator实例,二分法 public ArrayListSpliterator trySplit() { int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;//hi:结束位置(不包括) lo:开始位置 mid:中间位置 return (lo >= mid) ? null : // divide range in half unless too small new ArrayListSpliterator (list, lo, index = mid, //当lo>=mid,表示不能在分割,返回null expectedModCount); //当lo 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; } //顺序遍历处理所有剩下的元素 public void forEachRemaining(Consumer super E> action) { int i, hi, mc; // hoist accesses and checks from loop ArrayList lst; Object[] a; if (action == null) throw new NullPointerException(); if ((lst = list) != null && (a = lst.elementData) != null) { if ((hi = fence) < 0) { //当fence<0时,表示fence和expectedModCount未初始化, mc = lst.modCount; hi = lst.size; //由于上面判断过了,可以直接将lst大小给hi(不包括) } else mc = 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); } public int characteristics() { return Spliterator.ORDERED | Spliterator.SIZED | Spliterator.SUBSIZED; } } //根据Predicate条件来移除元素 将所有元素依次根据filter的条件判断 Predicate 是 传入元素 返回 boolean 类型的接口 @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)) { //如果元素满足条件 true 会留下 removeSet.set(i); //将满足条件的角标存放到set中 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); //把removeSet的元素放回原来数组 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 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]);//取出每一个元素给operator的apply方法 } if (modCount != expectedModCount) { throw new ConcurrentModificationException(); } modCount++; } //根据 Comparator条件进行排序 @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使用无参构建函数创建是创建了一个空数组,名字是DEFAULTCAPACITY_EMPTY_ELEMENTDATA,然后第一次使用add()添加的时候才会进行扩容,这是懒加载方式
使用有参构造函数创建,如果参数是0就创建一个空数组,名字是EMPTY_ELEMENTDATA,如果参数大于0,就用这个参数创建一个数组
add()方法流程:
先看需不需要扩容:minCapacity加1,如果当前数组是空数组DEFAULTCAPACITY_EMPTY_ELEMENTDATA,就用默认容量和+1后的minCapacity比较,取最大值为minCapacity,否则不用比较,然后判断是否比当前数组的长度大,是的话就调用grow方法进行扩容
grow方法:
先取当前数组长度,新数组长度为当前数组长度1.5倍,然后判断新数组长度是否小于minCapacity,小于的话就用minCapacity作为新数组长度,如果新数组长度大于数组长度的上限,再判断minCapacity是否大于数组长度的上限,是的话就把MAX_VALUE作为新数组长度,否的话把数组长度的上限作为新数组长度,最后调用Arrays.copyOf()方法把旧数组的值移到扩容后的数组
流程图如下



