一点一点看JDK源码(三)java.util.ArrayList

liuyuhang原创,未经允许禁止转载

本文举例使用的是JDK8的API

目录:一点一点看JDK源码(〇)

1.综述

  ArrayList是一个容量不固定的容器,为单列,有序集合,容量可扩容,扩容系数为1.5

  有最大值,一般达不到。

  ArrayList是线程不安全的,其扩容发生于集合修改的时候,如add,addAll等

  ArrayList底层使用的是Object数组,初始化内容为10个容量的元素

  使用ArrayList的时候,几种情况下实例化将更加提高效率

    ①仅仅使用基础增加功能作为容器临时使用

      List list = new ArrayList()

      这样可以使用较少的实例化方法

    ②使用ArrayList中的所有实例化方法时使用

      ArrayList list = new ArrayList()

      这样可以使用ArrayList所有的方法

    ③如果你能确定这个集合的容量,最好指定其容量,

      扩容也是一种算法,而且可能扩容多次,效率不高,如:

      ArrayList list = new ArrayList(22)

    ④如果该ArrayList的长度巨大,并且不确定,只用于容器临时使用

      建议使用LinkedList进行接收参数,然后再转化为ArrayList,如:

      LinkedList list = new LinkedList();

      //some operations

      ArrayList listArr = new ArrayList(list);

  

2.关注点

  • Collection
  • List
  • LinkedList
  • Vector

  关注点

    Collection为父接口的父接口

    List为父接口

    LinkedList为List的链表实现,ArrayList为List的数组实现

    Vector几乎不去用,他是List的另一种数组实现,但是线程安全

  虽然类注释上的@see只有这些,但是个人认为,

  应该重点关注一下AbstractList抽象类,RandomAccess,Cloneable这两个接口,序列化接口关注度真心不高

  对于接口的实现关系,哪些是List通用的,哪些内容已经在AbstractList抽象类中已经定义了,应该过一下的

3.源码解析

  放源码如下,注解有些删掉,对于类,内部类,方法,构造等进行了简要的说明注释

  内容比较多,建议慢慢看完,如果jdk1.8新增的看不懂,可以暂时搁置,略过

  我也不保证对于jdk1.8的部分注释是正确的。

 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; /**
* 以object数组作为类内共享实例容器。
*/
private static final Object[] EMPTY_ELEMENTDATA = {}; /**
* 以object数组作为类内共享实例容器,使用默认容量实例化时使用。
*/
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {}; /**
* 以object数组作为容器缓自排序冲数组,注意没有private关键字,用于排序,当地一个元素添加的时候将转为默认容量
*/
transient Object[] elementData; // non-private to simplify nested class access /**
* 缓存的size大小,
*/
private int size; /**
* 带参构造,手动设置容器初始大小,若实例化时能确定大小,最好别使用默认扩展容量,将提高运行效率
*/
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); //容量扩充参数异常
}
} /**
* 无参构造,使用默认容器初始化大小
*/
public ArrayList() {
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
} /**
* 带参构造器,将参数集合用数组工具类转成数组,并存入缓冲数组,对缓冲数组进行校验.
* 若转换后的数组并非object数组(内嵌套无法直接引用情况下),则使用数组工具类将该数组使用深度拷贝
*/
public ArrayList(Collection<? extends E> c) {
elementData = c.toArray();
if ((size = elementData.length) != 0) {
// c.toArray might (incorrectly) not return Object[] (see 6260652)
if (elementData.getClass() != Object[].class)
elementData = Arrays.copyOf(elementData, size, Object[].class);
} else {
// replace with empty array.
this.elementData = EMPTY_ELEMENTDATA;
}
} /**
* 去除多余的数组申请空间,在内存紧张时会用到
*/
public void trimToSize() {
modCount++;//修改次数
if (size < elementData.length) {
elementData = (size == 0)
? EMPTY_ELEMENTDATA
: Arrays.copyOf(elementData, size);
}
} /**
* 对底层缓冲数组进行扩容的优化方法,如果已知该ArrayList容量,则可执行一次性扩容,
* 否则将在数组add的过程中进行动态扩容,效率较低
*/
public void ensureCapacity(int minCapacity) {
int minExpand = (elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA)? 0: DEFAULT_CAPACITY;
if (minCapacity > minExpand) {
ensureExplicitCapacity(minCapacity);
}
}
/**
* 重新计算ArrayList的size,在使用构造和扩容时调用
*/
private static int calculateCapacity(Object[] elementData, int minCapacity) {
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
return Math.max(DEFAULT_CAPACITY, minCapacity);
}
return minCapacity;
} /**
* 被add调用,内部调用calculatecapacity,用于扩容
*/
private void ensureCapacityInternal(int minCapacity) {
ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
} /**
* 被ensureCapacity调用,内部调用calculatecapacity,用于扩容或优化
*/
private void ensureExplicitCapacity(int minCapacity) {
modCount++;
// overflow-conscious code
if (minCapacity - elementData.length > 0)
grow(minCapacity);
} /**
* 目标分配数组的容器大小,最大值要小于Integer.MAX_VALUE-8
*/
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8; /**
* 扩容
*/
private void grow(int minCapacity) {
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);
}
/**
* 被grow方法调用,扩容为最大
*/
private static int hugeCapacity(int minCapacity) {
if (minCapacity < 0) //参数错误,抛出异常
throw new OutOfMemoryError();
return (minCapacity > MAX_ARRAY_SIZE) ? Integer.MAX_VALUE : MAX_ARRAY_SIZE; //返回最大容量
} /**
* 获取当前size
*/
public int size() {
return size;
} /**
* 判断当前是size是否为0,容器是否为空
*/
public boolean isEmpty() {
return size == 0;
} /**
* 判断是否包含元素o,返回该元素的index是否大于等于0的判断,是为包含,否为不包含
*/
public boolean contains(Object o) {
return indexOf(o) >= 0;
} /**
* 获取查询元素的index,若备查元素为null,则寻找空元素,返回index
* 若备查元素不为null,则使用equal判断该元素是否存在,并返回index
* 不存在则返回-1
* 被contains调用
*/
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;
} /**
* clone本实例数组,返回类型为Object,使用根类意为可转换为其他格式容器
*/
public Object clone() {
try {
ArrayList<?> v = (ArrayList<?>) super.clone();
v.elementData = Arrays.copyOf(elementData, size);
v.modCount = 0;
return v;
} catch (CloneNotSupportedException e) {
throw new InternalError(e);
}
} /**
* 将本实例转换为object数组,调用数组工具类拷贝
*/
public Object[] toArray() {
return Arrays.copyOf(elementData, size);
} /**
* 将本实例转换为指定类型数组,调用数组工具类拷贝,并获得泛型的Class
*/
@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的元素,被get方法调用,get方法内进行check,util包内的类可调用
*/
@SuppressWarnings("unchecked")
E elementData(int index) {
return (E) elementData[index];
} /**
* 获取指定元素的方法,使用rangeCheck进行index的check
*/
public E get(int index) {
rangeCheck(index);
return elementData(index);
} /**
* 将指定index的值设置为指定值,使用rangeCheck进行index的check
*/
public E set(int index, E element) {
rangeCheck(index);
E oldValue = elementData(index);
elementData[index] = element;
return oldValue;
} /**
* 容量+1的,在容器尾部添加元素
*/
public boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e; // 这个在数组尾部追加元素的写法很好用,前提是扩容
return true; // 有返回值的,应当接收
} /**
* 在指定index添加指定元素,首先使用rangeCheckForAdd进行check,为保证数组操作的正确性,使用arraycopy来移动数组元素
*/
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++;
} /**
* remove指定index的元素,并重构本实例
*/
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;
} /**
* remove指定元素,返回是否找到该元素并移除成功的boolean标记
*/
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;
} /*
* 内部使用,快速移除指定index的元素
*/
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
} /**
* 清除本实例内部的所有元素,加速gc回收
*/
public void clear() {
modCount++;
// clear to let GC do its work
for (int i = 0; i < size; i++)
elementData[i] = null;
size = 0;
} /**
* 添加指定集合到本实例中Object数组末尾
*/
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;
} /**
* 从指定元素开始添加指定集合到本实例
*/
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;
} /**
* 本类和子类可使用,移除指定范围的index的所有元素
*/
protected void removeRange(int fromIndex, int toIndex) {
modCount++;
int numMoved = size - toIndex;
System.arraycopy(elementData, toIndex, elementData, fromIndex, numMoved);
int newSize = size - (toIndex-fromIndex);
for (int i = newSize; i < size; i++) {
elementData[i] = null;
}
size = newSize;
} /**
* 内部的index超限检测方法,当index超过size的时候,抛出index超限异常,在本类中被多次调用
*/
private void rangeCheck(int index) {
if (index >= size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
} /**
* 同上,但是在add和addAll中专用
*/
private void rangeCheckForAdd(int index) {
if (index > size || index < 0)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
} /**
* index超限抛异常时使用,用来提示size和index的值
*/
private String outOfBoundsMsg(int index) {
return "Index: "+index+", Size: "+size;
} /**
* 从本类实例中移除指定集合中所有元素的方法,返回值应接收
*/
public boolean removeAll(Collection<?> c) {
Objects.requireNonNull(c);
return batchRemove(c, false);
} /**
* 从本类实例中保留指定集合中所有元素的方法,与removeAll相反
*/
public boolean retainAll(Collection<?> c) {
Objects.requireNonNull(c);
return batchRemove(c, true);
} /**
* 内部调用,如果参数集合发生更改,则返回true
*/
private boolean batchRemove(Collection<?> c, boolean complement) {
final Object[] elementData = this.elementData; //获取本实例的所有元素
int r = 0, w = 0; //r用于遍历,w用于记录相同元素的数量,也用于记录容器的扩容标记
boolean modified = false; //标志位
try {
for (; r < size; r++)
if (c.contains(elementData[r]) == complement) //判断该元素是否被包含
elementData[w++] = elementData[r]; //包含则w++
} 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; //容量有变化,说明有交集,则返回true
}
}
return modified;
} /**
* 将本实例对象写入流中,实际上只写入了modCount,size和element[i],其余的内容在实例化时候是不必要的,或者可恢复的
*/
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
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迭代器
*/
public ListIterator<E> listIterator(int index) {
if (index < 0 || index > size)
throw new IndexOutOfBoundsException("Index: "+index);
return new ListItr(index);
} /**
* 获得本实例的默认List迭代器
*/
public ListIterator<E> listIterator() {
return new ListItr(0);
} /**
* 获得本实例的默认迭代器
*/
public Iterator<E> iterator() {
return new Itr();
} /**
* 内部使用的迭代器,重写自Iterator接口,为内部类
*/
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")
//重写迭代器提供next方法,可能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];
}
//重写迭代器提供remove方法
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")//重写迭代器接口下的forEachRemaining方法,可能unchecked报错,可使用lambda迭代
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修改次数的方法
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
} /**
* 另一个内部提供ListItr的迭代器,继承自上述内部类,实现ListIteraotr接口,本内部类将允许使用固定长度的迭代器
*/
private class ListItr extends Itr implements ListIterator<E> {
ListItr(int index) {
super();
cursor = index;
}
//是否有前一个元素
public boolean hasPrevious() {
return cursor != 0;
}
//获取下一个index
public int nextIndex() {
return cursor;
}
//获取前一个index
public int previousIndex() {
return cursor - 1;
}
//获取前一个元素,可能因为unchecked报错
@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];
}
//对迭代器内当index的元素设置为指定值
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();
}
}
} /**
* 从fromIndex到toIndex拆分数组,内部调用subListRangeCheck方法对本实例进行check
*/
public List<E> subList(int fromIndex, int toIndex) {
subListRangeCheck(fromIndex, toIndex, size);
return new SubList(this, 0, fromIndex, toIndex); //调用复写的内部类,十分巨大
}
/**
* 被内部调用,进行拆分时的参数check校验
*/
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 + ")");
} /**
* 重写继承的AbstractList中的SubList类,对于该类提供和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 = ArrayList.this.modCount;
}
//内部类的set方法
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;
}
//内部类的get方法
public E get(int index) {
rangeCheck(index);
checkForComodification();
return ArrayList.this.elementData(offset + index);
}
//内部类的size方法
public int size() {
checkForComodification();//复用
return this.size;
}
//内部类的add方法
public void add(int index, E e) {
rangeCheckForAdd(index); //复用
checkForComodification();//复用
parent.add(parentOffset + index, e);
this.modCount = parent.modCount;
this.size++;
}
//内部类的remove方法
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;
}
//内部类的addAll
public boolean addAll(Collection<? extends E> c) {
return addAll(this.size, c);
}
//内部类的addAll,从指定index开始
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;
}
//内部类的迭代器的next
@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)];
}
//剩余元素的迭代,可以使用lambda表达式进行遍历
@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();
}
//内部类的迭代器中获取下一个元素的index
public int nextIndex() {
return cursor;
}
//内部类的迭代器中获取上一个元素的index
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();
}
}
//内部类的迭代器中add方法添加元素到迭代器末尾
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();
}
}
//内部类的modCount校验
final void checkForComodification() {
if (expectedModCount != ArrayList.this.modCount)
throw new ConcurrentModificationException();
}
};
} /**
* 内部类的拆分list的方法
*/
public List<E> subList(int fromIndex, int toIndex) {
subListRangeCheck(fromIndex, toIndex, size);
return new SubList(this, offset, fromIndex, toIndex);
}
/**
* 内部类的index越界检查方法
*/
private void rangeCheck(int index) {
if (index < 0 || index >= this.size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
/**
* 同上,add和addAll专用
*/
private void rangeCheckForAdd(int index) {
if (index < 0 || index > this.size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
/**
* 内部类rangeCheckForAdd中抛异常调用,写明index和size
*/
private String outOfBoundsMsg(int index) {
return "Index: "+index+", Size: "+this.size;
}
/**
* 内部类的modCount校验
*/
private void checkForComodification() {
if (ArrayList.this.modCount != this.modCount)
throw new ConcurrentModificationException();
}
/**
* 内部类的分离迭代器函数,调用ArrayList的ArrayListSpliterator内部类的构造器
*/
public Spliterator<E> spliterator() {
checkForComodification();
return new ArrayListSpliterator<E>(ArrayList.this, offset, offset + this.size, this.modCount);
}
} /**
* 重写继承的forEach方法,用于迭代
*/
@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();
}
} /**
* jd1.8更新
* 重写自父类,分离数组,默认使用本类内容,从0-末尾,
*/
@Override
public Spliterator<E> spliterator() {
return new ArrayListSpliterator<>(this, 0, -1, 0);
} /**
* jd1.8更新
* 重写自父类,实现Spliterator接口
* 本类用于分离ArrayList,前提是ArrayList暂定是不变的,否则将可能出现线程错误
*/
static final class ArrayListSpliterator<E> implements Spliterator<E> { 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 /**
* 内部类ArrayListSpliterator的构造器
*/
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;
}
/**
* 内部类ArrayListSpliterator中很多方法都使用的初始化方法
*/
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;
}
/**
* 内部类ArrayListSpliterator的拆分arraylist方法,不保证结果正确
*/
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);
} /**
* 内部类ArrayListSpliterator的预拆分?尝试是否能够拆分
*/
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;
} /**
* 内部类ArrayListSpliterator迭代
*/
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();
}
//内部类ArrayListSpliterator的size预估
public long estimateSize() {
return (long) (getFence() - index);
} //分离参数初始化
public int characteristics() {
return Spliterator.ORDERED | Spliterator.SIZED | Spliterator.SUBSIZED;
}
} /**
* 重写自父类,使用重写的filter接口进行筛选,符合条件的则移除
*/
@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;
} /**
* 重写自父类,使用重写的operator接口进行替代本实例中匹配的元素
*/
@Override
@SuppressWarnings("unchecked")
public void replaceAll(UnaryOperator<E> operator) {
Objects.requireNonNull(operator);
final int expectedModCount = modCount;
final int size = this.size;
for (int i=0; modCount == expectedModCount && i < size; i++) {
elementData[i] = operator.apply((E) elementData[i]);
}
if (modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
modCount++;
} /**
* 重写自父类,使用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++;
}
}

  本篇注释前偏,只是粗略的了解,中篇 和 后篇 将对其中的使用进行总结和举例。

以上!

05-11 09:38