ArrayList源码分析
1. 下面是ArrayList的继承体系结构

从上图可以看出ArrayList的继承体系:
1. 继承AbstractList,实现List,它是一个数组队列,提供了相关的添加、删除、修改、遍历等功能
2. 实现RandomAccess接口,实现快速随机访问:通过元素的序号快速获取元素对象
3. 实现Cloneable接口, 重写了clone(), 可以进行克隆(浅拷贝)
4. 实现Serialiazable接口, 可以实现序列化
2. ArrayList的数据结构
2.1 重要的全局变量
/** * Default initial capacity. * 在初次进行元素添加的时候初始化的数组长度 */ 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. * 使用默认构造器创建ArrayList的对象时默认使用的一个空数组 */ 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的底层数组 */ transient 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; /** * 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 * ArrayList的允许的最大元素个数 */ private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
2.2 构造器
/** * Constructs an empty list with the specified initial capacity. * 创建一个指定容量的空列表,如果传入的参数为零,这使用一个默认已经创建好的空列表 * 如果参数小于0,这会抛出异常 * @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. * 默认的构造器,初始化容量为0,在第一个元素新增时 * 使用DEFAULT_CAPACITY(10)完成有容量的初始化 */ 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对象直接转换为ArrayList * @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(); //如果存在元素,且数组中的元素不是Object类型的,则进行转换并赋给ArrayList的底层数组 if ((size = elementData.length) != 0) { // c.toArray might (incorrectly) not return Object[] (see 6260652) if (elementData.getClass() != Object[].class) elementData = Arrays.copyOf(elementData, size, Object[].class); } else { //创建一个空容量的数组 // replace with empty array. this.elementData = EMPTY_ELEMENTDATA; } }
3. 常用方法的分析
/* * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. */ package java.util; import java.util.function.Consumer; import java.util.function.Predicate; import java.util.function.UnaryOperator; public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable { private static final long serialVersionUID = 8683452581122892189L; /** * Default initial capacity. * 在初次进行元素添加的时候初始化的底层数组长度 */ private static final int DEFAULT_CAPACITY = 10; /** * Shared empty array instance used for empty instances. * 默认创建的一个没有容量的空数组 */ private static final Object[] EMPTY_ELEMENTDATA = {}; /** * 默认创建的一个没有容量的空数组 * 使用默认构造器创建ArrayList的对象时 * 底层数组是指向该对象 */ private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {}; /** * ArrayList的底层数组 * 使用default修饰符,可以让本包的类访问 */ transient Object[] elementData; /** * The size of the ArrayList (the number of elements it contains). * 记录ArrayList中元素的个数,区别于底层数组的容量 */ private int size; /** * Constructs an empty list with the specified initial capacity. * 创建一个指定容量的空列表 */ public ArrayList(int initialCapacity) { if (initialCapacity > 0) { this.elementData = new Object[initialCapacity]; } else if (initialCapacity == 0) { //等于0,则指向默认创建的没有容量的空数组对象 this.elementData = EMPTY_ELEMENTDATA; } else { //小于0则抛出异常 throw new IllegalArgumentException("Illegal Capacity: "+ initialCapacity); } } /** * Constructs an empty list with an initial capacity of ten. * 底层数组默认指向一个没有容量的空数组对象 * 在第一个元素新增时 * 使用DEFAULT_CAPACITY(10)完成有容量的初始化 */ public ArrayList() { this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA; } /** * 接受一个Collection对象,并将其转换为ArrayList中的元素 */ public ArrayList(Collection<? extends E> c) { //底层的动态数组 elementData = c.toArray(); //如果存在元素,且数组中的元素不是Object类型的,则进行转换并赋给ArrayList的底层数组 if ((size = elementData.length) != 0) { // c.toArray might (incorrectly) not return Object[] (see 6260652) if (elementData.getClass() != Object[].class) elementData = Arrays.copyOf(elementData, size, Object[].class); } else { //创建一个空容量的数组 this.elementData = EMPTY_ELEMENTDATA; } } /** * 在底层数组的长度大于size的大小的时候, * 进行底层数组的长度的矫正 */ public void trimToSize() { modCount++; 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. * 没有使用的方法 * @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); } } /** * 在添加元素钱进行调用 * 检查是否需要进行扩容 * @param minCapacity */ private void ensureCapacityInternal(int minCapacity) { //如果是第一次添加,则初始化底层数组的长度为10 if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) { minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity); } //检查是否需要扩容 ensureExplicitCapacity(minCapacity); } /** * 检查是否需要扩容 * @param minCapacity */ private void ensureExplicitCapacity(int minCapacity) { modCount++; // overflow-conscious code if (minCapacity - elementData.length > 0) grow(minCapacity); //执行扩容的方法 } /** * ArrayList的允许的最大元素个数 * 一些jvm的实现的java对象header会占据8位,所以这会进行-8. * 但其实是可以允许达到Integer的最大值的 */ private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8; /** * 进行底层数组的扩容 * 将容量扩大到原数组长度的1.5倍 * * @param minCapacity the desired minimum capacity */ private void grow(int minCapacity) { // overflow-conscious code int oldCapacity = elementData.length; //底层数组现在的长度 int newCapacity = oldCapacity + (oldCapacity >> 1); //扩容后的长度,将原数组的长度扩大到原来的1.5倍 //对扩容后的底层数组长度进行校正 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); } /** * 大于允许的元素的最大数量时进行校正 * @param minCapacity * @return */ private static int hugeCapacity(int minCapacity) { if (minCapacity < 0) // overflow throw new OutOfMemoryError(); return (minCapacity > MAX_ARRAY_SIZE) ? Integer.MAX_VALUE : MAX_ARRAY_SIZE; } /** * 获取ArrayList中元素的个数 */ public int size() { return size; } /** * 判断ArrayList是否为空,即是否包含元素 */ public boolean isEmpty() { return size == 0; } /** * 判断集合中是否包含某个元素 * 包含返回true,不包含返回false */ public boolean contains(Object o) { return indexOf(o) >= 0; } /** * 返回元素所在集合的位置 * 不存在返回-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; } /** * ArrayList中的元素是允许重复的 * 获取某个元素最后所在集合的位置 * 不存在则返回-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); v.modCount = 0; return v; } catch (CloneNotSupportedException e) { // this shouldn't happen, since we are Cloneable throw new InternalError(e); } } /** * 将集合对象转换为一个Object类型的数组 */ public Object[] toArray() { return Arrays.copyOf(elementData, size); } /** * 返回一个给定类型的数组 */ @SuppressWarnings("unchecked") public <T> T[] toArray(T[] a) { if (a.length < size) // Make a new array of a's runtime type, but my contents: return (T[]) Arrays.copyOf(elementData, size, a.getClass()); System.arraycopy(elementData, 0, a, 0, size); if (a.length > size) a[size] = null; return a; } /** * 返回指定位置的底层数组的元素 */ @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); // Increments modCount!! elementData[size++] = e; 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); //将元素存放在指定的位置 elementData[index] = element; size++; } /** * 移除指定索引位置的元素 * 并返回移除的元素 */ public E remove(int index) { //检查索引的合理性 rangeCheck(index); modCount++; //获取到要移除的元素 E oldValue = elementData(index); //需要移动的元素的个数 int numMoved = size - index - 1; //将该索引之后的元素往前移动 if (numMoved > 0) System.arraycopy(elementData, index+1, elementData, index, numMoved); elementData[--size] = null; // clear to let GC do its work return oldValue; } /** * 移除指定的元素 * 成功返回true * 失败则返回false */ public boolean remove(Object o) { //元素为null的话,则移除第一个查找到的null 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; } /** * 添加一个Collection对象到集合中 */ public boolean addAll(Collection<? extends E> c) { //将collection对象转换为数组 Object[] a = c.toArray(); int numNew = a.length; //检查是否需要扩容 ensureCapacityInternal(size + numNew); // Increments modCount //添加元素 System.arraycopy(a, 0, elementData, size, numNew); size += numNew; return numNew != 0; } /** * 在指定的位置添加一个collection对象 */ public boolean addAll(int index, Collection<? extends E> c) { //检查索引的合理性 rangeCheckForAdd(index); Object[] a = c.toArray(); int numNew = a.length; //检查是否需要扩容 ensureCapacityInternal(size + numNew); // Increments modCount int numMoved = size - index; //先把指定位置及其之后的元素往后移动 if (numMoved > 0) System.arraycopy(elementData, index, elementData, index + numNew, numMoved); //在将collection对象的元素添加到集合中 System.arraycopy(a, 0, elementData, index, numNew); size += numNew; return numNew != 0; } /** * 移除指定范围的元素 * 只能在子类中使用 */ protected void removeRange(int fromIndex, int toIndex) { modCount++; //将需要移除的最后一个元素后面的所有元素往前移动 int numMoved = size - toIndex; System.arraycopy(elementData, toIndex, elementData, fromIndex, numMoved); //将移动后后面的那些指定为null,加快gc的回收 // 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 void rangeCheckForAdd(int index) { if (index > size || index < 0) throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); } /** * 下标越界时打印的信息 */ private String outOfBoundsMsg(int index) { return "Index: "+index+", Size: "+size; } /** * 如何集合中包含collection对象中的元素 * 则进行移除,如果有重复的元素,则全部移除 */ public boolean removeAll(Collection<?> c) { //判断collection对象是否为null Objects.requireNonNull(c); //进行元素的移除 return batchRemove(c, false); } /** * 只保留同时存在于集合和collection对象中的元素 */ public boolean retainAll(Collection<?> c) { Objects.requireNonNull(c); return batchRemove(c, true); } /** * 移除集合中包含的collection对象中的元素 * @param c * @param complement * @return */ private boolean batchRemove(Collection<?> c, boolean complement) { //获取集合的底层数组 final Object[] elementData = this.elementData; int r = 0, w = 0; boolean modified = false; try { //循环判断collection中的元素是否存在于集合中 //并根据complement的值来决定是移除存在 元素还是只保留存在的元素 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. //将r之后的元素往前移动 if (r != size) { System.arraycopy(elementData, r, elementData, w, size - r); w += size - r; } //将w之后的元素指定为null,并重新调整集合的size大小 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); // Write out all elements in the proper order. for (int i=0; i<size; i++) { s.writeObject(elementData[i]); } if (modCount != expectedModCount) { throw new ConcurrentModificationException(); } } /** * 反序列化集合中的元素 */ private void readObject(java.io.ObjectInputStream s) throws java.io.IOException, ClassNotFoundException { elementData = EMPTY_ELEMENTDATA; // Read in size, and any hidden stuff s.defaultReadObject(); // Read in capacity s.readInt(); // ignored if (size > 0) { // be like clone(), allocate array based upon size not capacity ensureCapacityInternal(size); Object[] a = elementData; // Read in all elements in the proper order. for (int i=0; i<size; i++) { a[i] = s.readObject(); } } } /** * 从指定位置开始返回一个listIterator */ public ListIterator<E> listIterator(int index) { if (index < 0 || index > size) throw new IndexOutOfBoundsException("Index: "+index); return new ListItr(index); } /** * 返回一个listIterator */ 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; //判断迭代器中是否还有元素 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; //修改cursor的值 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(); } } /** * java8新增的方法 * 对每个元素执行给定的方法,依次处理,直到所有元素已被处理或被异常终止 * 默认方法调用tryAdvance方法 */ @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(); } } /** * ArrayList独有的迭代器 */ 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(); } } } /** * 从指定位置开始截断集合,并返回截断后的集合 */ public List<E> subList(int fromIndex, int toIndex) { //检查截断的起始索引是否合理 subListRangeCheck(fromIndex, toIndex, size); return new SubList(this, 0, fromIndex, toIndex); } /** * 检查起始索引的合理性 * @param fromIndex * @param toIndex * @param size */ 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 + ")"); } /** * 一个内部类,将集合截断后返回的对象 * 跟ArrayList的结构一样
* 省略掉内容 * @author Administrator * */ private class SubList extends AbstractList<E> implements RandomAccess { } /** * java8新增加的方法 * 根据传入的lambda表达式 * 遍历集合中的元素 * 不是线程安全的 */ @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(); } } /** * java8新增的方法 * 返回一个并行的分片迭代器 */ @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> { private final ArrayList<E> list; //起始位置(包含)advance/split操作时会修改 private int index; // current index, modified on advance/split //结束位置(不包含) -1 表示到最后一个元素 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; } /** * 获取结束位置,主要用于第一次使用时对fence的初始化赋值 */ 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) { //当list为空,fence=0 if ((lst = list) == null) hi = fence = 0; else { //否则fence等于list的长度 expectedModCount = lst.modCount; hi = fence = lst.size; } } return hi; } /** * 对任务(list)分割,返回一个新的Spliterator迭代器 */ 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); } /** * 对单个元素执行给定的执行方法 * 若没有元素需要执行,返回false;若可能还有元素尚未执行,返回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); //执行传入的lambda表达式 if (list.modCount != expectedModCount) throw new ConcurrentModificationException(); return true; } return false; } /** * 对每个元素执行给定的方法,依次处理,直到所有元素已被处理或被异常终止 * 默认方法调用tryAdvance方法 */ 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; } } /** * java8新增的方法 * 传入一个lambda表达式 * 移除满足规则的元素 * 不是线程安全的 */ @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; //遍历查找满足规则的元素,并将元素的位置放入bitSet中 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]; } //将newSize后面的元素置为null,让gc进行垃圾回收 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; } /** * java8新增的方法 * 按照指定的规替换集合中的元素 */ @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++; } /** * java8新增的一个方法 * 传入一个lambda表达式 * 对集合中的元素进行排序 */ @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++; } }
仰望星空,脚踏实地,我们在路上

浙公网安备 33010602011771号