java8 ArrayList源码阅读
2017-04-16 01:23
363 查看
阅读了ArrayList源码的实现,并对源码做了相关注释,如下:
以下内容基于jdk1.8.0_121的ArrayList的源码。
【如果觉得代码太长,可直接看另一篇《 java8 ArrayList源码阅读【2】- 总结》】
以上就是ArrayList源码的内容了,也就大概1000多行吧,看着也挺容易理解的,接下来会针对ArrayList源码做个小结。
以下内容基于jdk1.8.0_121的ArrayList的源码。
【如果觉得代码太长,可直接看另一篇《 java8 ArrayList源码阅读【2】- 总结》】
/* * ArrayList 源码阅读 * Created by wbin on 2017/4/15. */ 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; //默认初始容量为10 private static final int DEFAULT_CAPACITY = 10; //空数组实例 private static final Object[] EMPTY_ELEMENTDATA = {}; //存储数据的数组,由此可看出ArrayList内部是用数组实现的 transient Object[] elementData; // non-private to simplify nested class access //容量 private int size; //构造方法,创建指定容量大小的数组。如果容量大小为负则会抛出异常 public ArrayList(int initialCapacity) { super(); if (initialCapacity < 0) throw new IllegalArgumentException("Illegal Capacity: " + initialCapacity); this.elementData = new Object[initialCapacity]; } //默认构造方法,使用空数组初始化,容量大小默认为0 public ArrayList() { super(); this.elementData = EMPTY_ELEMENTDATA; } //构造一个包含指定集合的元素的列表,按照它们由集合的迭代器返回的顺序。 public ArrayList(Collection<? extends E> c) { elementData = c.toArray(); size = elementData.length; // c.toArray 可能不返回Object[] (see 6260652) if (elementData.getClass() != Object[].class) elementData = Arrays.copyOf(elementData, size, Object[].class); } //释放数组空余的空间,容量为数组实际元素数量(因为容量通常会大于实际元素数量, //扩充方法为增大1.5倍,见下grow()方法),可以在内存紧张时调用。 public void trimToSize() { modCount++; //涉及数组的改变,modCount都会改变,留意该变量,后面会频繁出现 if (size < elementData.length) { //如果数组实际元素数量比数组容量小,则重新赋值数组释放多余空间 elementData = Arrays.copyOf(elementData, size); } } //使用指定参数设定最小容量 public void ensureCapacity(int minCapacity) { //如果数组为空,容量预取0,否则去默认值10 int minExpand = (elementData != EMPTY_ELEMENTDATA) // any size if real element table ? 0 // larger than default for 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 == EMPTY_ELEMENTDATA) { minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity); } ensureExplicitCapacity(minCapacity); } //根据指定参数增加数组容量 private void ensureExplicitCapacity(int minCapacity) { modCount++; //上面提到,只要涉及数组结构的改变(这里是数组大小改变),该变量改变 //如果参数大于数组容量,就增加数组容量 if (minCapacity - elementData.length > 0) grow(minCapacity); } //数组的最大容量,可能会导致内存溢出(VM内存限制) private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8; //增加容量,以确保它可以至少持有由参数指定的元素的数目 private void grow(int minCapacity) { // overflow-conscious code int oldCapacity = elementData.length; //新容量为原来的1.5倍 int newCapacity = oldCapacity + (oldCapacity >> 1); //如果仍比参数小,则新容量大小取参数的值 if (newCapacity - minCapacity < 0) newCapacity = minCapacity; //若新容量大于默认的最大值,则检查是否溢出 if (newCapacity - MAX_ARRAY_SIZE > 0) newCapacity = hugeCapacity(minCapacity); elementData = Arrays.copyOf(elementData, newCapacity); } //检查参数是否溢出 private static int hugeCapacity(int minCapacity) { if (minCapacity < 0) // 溢出 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; } //是否包含特定元素,利用indexOf方法 public boolean contains(Object o) { return indexOf(o) >= 0; } //返回特定元素在数组首次出现的位置(遍历的方式),会根据是否为null使用不同方式判断。不存在就返回-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; //不存在返回-1 } //返回特定元素在数组最后一次出现的位置(遍历的方式),会根据是否为null使用不同方式判断。不存在就返回-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 { //java.lang.Object.clone()只是一种浅复制,所以,v的elementData引用的还是当前ArrayList的elementData的引用 java.util.ArrayList<?> v = (java.util.ArrayList<?>) super.clone(); //对原来ArrayList的elementData进行一个数组拷贝,然后赋值给v的elementData //这样,v的elementData就是原先ArrayList的elementData的一个副本,不再是内存中同一块数组 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); } } //返回一个包含此列表中所有元素的数组,使用Arrays.copyOf()方法(浅拷贝),与clone情况类似 public Object[] toArray() { return Arrays.copyOf(elementData, size); } //返回一个数组,使用运行时确定类型,该数组包含在这个列表中的所有元素(从第一到最后一个元素) 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()); //否则复制参数数组的前n个元素为原数组元素 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) { //确保容量,需要改变modCount值 ensureCapacityInternal(size + 1); elementData[size++] = e; return true; } //在指定位置添加新元素 public void add(int index, E element) { //检查位置合法 rangeCheckForAdd(index); ensureCapacityInternal(size + 1); // Increments modCount!! //从添加位置整体右移一位,因此arrayList添加元素是需要代价的 System.arraycopy(elementData, index, elementData, index + 1, size - index); elementData[index] = element; size++; } //删除指定位置的元素,返回删除的元素 public E remove(int index) { //检查位置合法 rangeCheck(index); //数组改变,modCount需要++ 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; } //删除指定元素首次出现的位置,若不存在则不改变 public boolean remove(Object o) { if (o == null) { for (int index = 0; index < size; index++) if (elementData[index] == null) { //由于位置一定合法,因此可以不用检查位置合法性,调用fastRemove方法即可。 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 } //清空数组,全部赋值为null,方便垃圾回收 public void clear() { //数组改变,modCount++ modCount++; // clear to let GC do its work for (int i = 0; i < size; i++) elementData[i] = null; size = 0; } //添加一个集合的元素到末端,若要添加的集合为空返回false 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); size += numNew; return numNew != 0; } //从指定位置添加一个集合的元素,若要添加的集合为空返回false 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); System.arraycopy(a, 0, elementData, index, numNew); size += numNew; return numNew != 0; } //删除指定范围内元素 protected void removeRange(int fromIndex, int toIndex) { //数组改变,modCount++ modCount++; int numMoved = size - toIndex; 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; } size = newSize; } //检查指定位置是否超出数组长度,用于添加元素时 private void rangeCheck(int index) { if (index >= size) throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); } //检查指定位置是否合法(小于0或超出数组长度) 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); //检查集合是否为空 return batchRemove(c, false); //调用batchRemove,complement为false } //与removeAll相反,仅保留指定集合的元素 public boolean retainAll(Collection<?> c) { Objects.requireNonNull(c); //检查集合是否为空 return batchRemove(c, true); //调用batchRemove,complement为true } //complement true时从数组保留指定集合中元素的值,为false时从数组删除指定集合中元素的值。 private boolean batchRemove(Collection<?> c, boolean complement) { final Object[] elementData = this.elementData; int r = 0, w = 0; //w为数组更新后的大小 boolean modified = false; try { //遍历数组,并检查元素是否在指定集合中,根据complement的值保留特定值到数组 //若complement为true即保留,则将相同元素移动到数组前端 //若complement为false即删除,则将不同元素移动到数组前端 for (; r < size; r++) if (c.contains(elementData[r]) == complement) elementData[w++] = elementData[r]; } finally { //如果r!=size则说明c.contains(elementData[r])抛出异常 if (r != size) { //将数组未遍历的部分添加 System.arraycopy(elementData, r, elementData, w, size - r); w += size - r; } //如果w!=size说明进行了删除操作,故需将删除的值赋为null 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; } //保存数组实例的状态到一个流(即它序列化)。写入过程数组被更改(利用modCount的值)会抛出异常 private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException { // Write out element count, and any hidden stuff int expectedModCount = modCount; //写入前modCount的值,将依据此检查写入过程数组是否被更改 s.defaultWriteObject(); // 写入容量大小 s.writeInt(size); // 按顺序写入数组元素 for (int i = 0; i < size; i++) { s.writeObject(elementData[i]); } // 若写入前后modCount值不同,说明写入过程数组被更改,则抛出异常 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 java.util.ArrayList.ListItr(index); } //返回ListIterator,开始位置为0 public ListIterator<E> listIterator() { return new java.util.ArrayList.ListItr(0); } //返回普通迭代器 public Iterator<E> iterator() { return new java.util.ArrayList.Itr(); } // 迭代器实现,AbstractList.Itr的优化版本 private class Itr implements Iterator<E> { int cursor; //游标,下一个元素的索引,默认初始化为0 int lastRet = -1; //上次访问的元素的位置,初始化为-1 int expectedModCount = modCount; //迭代过程不允许修改数组 //是否还有下一个 public boolean hasNext() { return cursor != size; } //下一个元素 @SuppressWarnings("unchecked") public E next() { //检查数组是否修改,根据expectedModCount和modCount判断 checkForComodification(); int i = cursor; if (i >= size) throw new NoSuchElementException(); Object[] elementData = java.util.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(); //检查数组是否修改,根据expectedModCount和modCount判断 checkForComodification(); try { java.util.ArrayList.this.remove(lastRet); cursor = lastRet; lastRet = -1; expectedModCount = modCount; //由于数组修改,重新设置expectedModCount } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } } //为每个剩余元素执行给定的操作,直到所有的元素都已经被处理或行动将抛出一个异常 @Override @SuppressWarnings("unchecked") public void forEachRemaining(Consumer<? super E> consumer) { Objects.requireNonNull(consumer); //consumer不为空 final int size = java.util.ArrayList.this.size; int i = cursor; if (i >= size) { return; } final Object[] elementData = java.util.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(); } //检查数组是否修改,根据expectedModCount和modCount判断 final void checkForComodification() { if (modCount != expectedModCount) throw new ConcurrentModificationException(); } } //ListIterator迭代器实现,可以双向移动,AbstractList.ListItr的优化版本 private class ListItr extends java.util.ArrayList.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 = java.util.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 { java.util.ArrayList.this.set(lastRet, e); } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } } //在当前位置添加新元素 public void add(E e) { checkForComodification(); //检查数组是否修改 try { int i = cursor; java.util.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 java.util.ArrayList.SubList(this, 0, fromIndex, toIndex); } //检查指定范围的参数合法,是否越界或小于0等 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 + ")"); } //子list的实现,方法于上述类似,类比即可 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 = java.util.ArrayList.this.modCount; } public E set(int index, E e) { rangeCheck(index); checkForComodification(); E oldValue = java.util.ArrayList.this.elementData(offset + index); java.util.ArrayList.this.elementData[offset + index] = e; return oldValue; } public E get(int index) { rangeCheck(index); checkForComodification(); return java.util.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 = java.util.ArrayList.this.modCount; public boolean hasNext() { return cursor != java.util.ArrayList.SubList.this.size; } @SuppressWarnings("unchecked") public E next() { checkForComodification(); int i = cursor; if (i >= java.util.ArrayList.SubList.this.size) throw new NoSuchElementException(); Object[] elementData = java.util.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 = java.util.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 = java.util.ArrayList.SubList.this.size; int i = cursor; if (i >= size) { return; } final Object[] elementData = java.util.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 { java.util.ArrayList.SubList.this.remove(lastRet); cursor = lastRet; lastRet = -1; expectedModCount = java.util.ArrayList.this.modCount; } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } } public void set(E e) { if (lastRet < 0) throw new IllegalStateException(); checkForComodification(); try { java.util.ArrayList.this.set(offset + lastRet, e); } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } } public void add(E e) { checkForComodification(); try { int i = cursor; java.util.ArrayList.SubList.this.add(i, e); cursor = i + 1; lastRet = -1; expectedModCount = java.util.ArrayList.this.modCount; } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } } final void checkForComodification() { if (expectedModCount != java.util.ArrayList.this.modCount) throw new ConcurrentModificationException(); } }; } public List<E> subList(int fromIndex, int toIndex) { subListRangeCheck(fromIndex, toIndex, size); return new java.util.ArrayList.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 (java.util.ArrayList.this.modCount != this.modCount) throw new ConcurrentModificationException(); } public Spliterator<E> spliterator() { checkForComodification(); return new java.util.ArrayList.ArrayListSpliterator<E>(java.util.ArrayList.this, offset, offset + this.size, this.modCount); } } //遍历每个元素做指定操作,java8新增方法 @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(); } } //返回Spliterator,用于多线程,java8新添加的 @Override public Spliterator<E> spliterator() { return new java.util.ArrayList.ArrayListSpliterator<>(this, 0, -1, 0); } //Spliterator的实现,java8新增方法,该类还需学习了解。 static final class ArrayListSpliterator<E> implements Spliterator<E> { private final java.util.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(java.util.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) java.util.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 java.util.ArrayList.ArrayListSpliterator<E> trySplit() { int hi = getFence(), lo = index, mid = (lo + hi) >>> 1; return (lo >= mid) ? null : // divide range in half unless too small new java.util.ArrayList.ArrayListSpliterator<E>(list, lo, index = mid, expectedModCount); } //对下一个为处理的操作执行action并返回true, 如果没有下一个元素,返回false public boolean tryAdvance(Consumer<? super E> action) { if (action == null) throw new NullPointerException(); int hi = getFence(), i = index; if (i < hi) { index = i + 1; @SuppressWarnings("unchecked") E e = (E) list.elementData[i]; action.accept(e); 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 java.util.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新增方法 @Override public boolean removeIf(Predicate<? super E> filter) { Objects.requireNonNull(filter); //检查filter是否为空 int removeCount = 0; //记录要删除的数目 final BitSet removeSet = new BitSet(size); //利用BitSet来记录删除元素的下标 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]; //如果当前元素符合条件,则BitSet标记当前下标 if (filter.test(element)) { removeSet.set(i); removeCount++; } } if (modCount != expectedModCount) { throw new ConcurrentModificationException(); } final boolean anyToRemove = removeCount > 0; //根据removeCount变量判断是否有满足条件的元素 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]; } //将更新后的数组没用的元素置null 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进行替换,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++; } //根据Comparator排序,java8新增方法 @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源码的内容了,也就大概1000多行吧,看着也挺容易理解的,接下来会针对ArrayList源码做个小结。
相关文章推荐
- java8 ArrayList源码阅读【2】- 总结
- java8 ArrayList源码阅读
- Java源码阅读之ArrayList
- Java源码阅读——ArrayList
- Java源码阅读之ArrayList
- [Java集合源码阅读]-ArrayList扩容机制
- Java源码阅读之ArrayList(1)
- Java源码阅读之ArrayList
- Java源码阅读-ArrayList
- Java源码阅读之ArrayList(4)
- Java源码阅读之ArrayList(终)
- Java源码阅读笔记-ArrayList
- Java源码阅读之ArrayList(3)
- java源码阅读系列-ArrayList
- JAVA 集合类(java.util)源码阅读笔记------ArrayList
- Java源码阅读-ArrayList
- java1.7集合源码阅读:ArrayList
- 重拾Java之ArrayList源码阅读
- Java源码解读之util.ArrayList
- java 集合ArrayList及LinkList源码分析