前言
终于等到你,我们最熟悉的 ArrayList
ArrayList 类描述
List 接口的动态数组实现。实现了所有可选操作,并且允许 null 元素。除了实现 List 接口以外,这个类还提供了改变内部数组大小的方法。这个类和 Vector 差不多,只是这个类不是线程安全的。
size, isEmpty, get, set, iterator, listIterator 的时间复杂度是常数量级的。 add 操作在 add n 个元素时,平均时间复杂度为 O(n)。其他所有操作的运行时间差不多都是线性的时间。性能会比 LinkedList 好。
每个 ArrayList 实例有一个容量(capacity)。容量是 list 用来存储元素的那个数组的大小。它一般至少要和 list 大小相等。当元素被添加进 ArrayList 时,它会自动扩容。扩容细节没有详细说明。
应用程序在添加大量的元素之前,可以使用 ensureCapacity 进行扩容,这样可以避免多次的扩容。
注意,这个实现是线程不安全的。如果多线程并发访问一个 ArrayList 实例,并且至少有一个线程修改了这个 list 的结构,那么必须在外部进行同步。(结构性修改是指增加或者删除元素,或者改变底层数组大小,只修改值不算结构性修改)一般是将 list 封装起来,在外部进行同步。如果没有封装,list 必须被 Collections.synchronizedList 方法包装,最好是像下面这样在创建时就包装防止线程不安全。
List list = Collections. synchronizedList(new ArrayList(...));
由 iterator 和 listIterator 方法返回的迭代器是快速失败(fail-fast)的:如果 list 在创建后在任何时间发生结构性修改,除非是迭代器自己进行的 add 或者 remove,否则就会抛出并发修改异常。因此,面对并发修改,迭代器会快速、明确地失败,而不会冒着之后出现什么不可以预测的事情的风险。
注意,快速失败行为无法保证。也就是说,未同步的并发修改不可能作出任何严格的保证。快速失败迭代器只是尽力抛出并发修改异常,因此你不能依赖于这个异常来保证代码的安全。这个只作为检测 bug 的手段。
ArrayList 类定义
类定义如下。此类实现了 RandomAccess, Cloneable 接口。这两个接口都是标记接口,就是一个空的接口,实现标记接口就是标记说明这个类是支持随机访问、支持克隆的。
public class ArrayList<E> extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{
// xxx....
}
ArrayList 类内容
内部属性
定义了以下字段,我用注释来解释。
/**
* 序列号,就是防止版本不对劲的东西。
*/
private static final long serialVersionUID = 8683452581122892189L;
/**
* 默认容量是 10
*/
private static final int DEFAULT_CAPACITY = 10;
/**
* 空数组。这个就是用来装元素的东西。
*/
private static final Object[] EMPTY_ELEMENTDATA = {};
/**
* 共享空数组实例用于默认大小的空实例。我们将其与 EMPTY_ELEMENTDATA 区分开来,以便知道在添加
* 第一个元素时要膨胀多少。
*/
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
/**
* 存储元素的缓冲区。这个一会在内部迭代器实现时候可以看到作用很大。
* 任何 elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA 的空数组,在第一次添加元素时
* 都会将容量扩充到 DEFAULT_CAPACITY 。这个不是 private 的,因为要用内部类去访问它。
*/
transient Object[] elementData;
/**
* 元素个数
*/
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;
}
指定集合的构造函数。将指定集合转化为数组,然后如果指定集合就是 ArrayList,直接将数组的引用赋值给成员变量,如果不是就使用 Arrays.copyOf 赋值。
public ArrayList(Collection<? extends E> c) {
Object[] a = c.toArray();
if ((size = a.length) != 0) {
if (c.getClass() == ArrayList.class) {
elementData = a;
} else {
elementData = Arrays.copyOf(a, size, Object[].class);
}
} else {
// replace with empty array.
elementData = EMPTY_ELEMENTDATA;
}
}
trimToSize
将容量修剪到 size 的大小。注意分清 capacity 和 size
public void trimToSize() {
modCount++;
if (size < elementData.length) {
elementData = (size == 0)
? EMPTY_ELEMENTDATA
: Arrays.copyOf(elementData, size);
}
}
ensureCapacity
这个方法就是为了直接扩容到指定的容量,防止你一次塞大量数据频繁扩容。这个在描述中提到过。里面做了一些优化,详细说一下
逻辑比较乱,总结一下,分两种情况
情况1:数组就是默认的空数组,默认空数组的容量是10,此时你指定 5 没用,不会变5,还是10.,如果你指定超过 10 的,那会扩容到你指定的数。
情况2:不是默认的空数组,minExpand 会等于 0,因此会触发进一步的扩容检查,在ensureExplicitCapacity(minCapacity)方法中实现。
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);
}
}
calculateCapacity
同样道理,和上面的那个属于组合拳,这个还是分两种情况。
情况1:默认的空数组,指定的大于 10 才行,否则就返回10
情况2:不是默认的空数组,直接返回那个给定的容量。
private static int calculateCapacity(Object[] elementData, int minCapacity) {
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
return Math.max(DEFAULT_CAPACITY, minCapacity);
}
return minCapacity;
}
ensureCapacityInternal
组合拳之一,扩容到指定的容量,但是中间用上面方法判断了一下。具体扩容实现在ensureExplicitCapacity中。
private void ensureCapacityInternal(int minCapacity) {
ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
}
ensureExplicitCapacity
扩容到指定容量。modCount++记录结构性修改。然后判断是不是指定容量大于 数组长度,是的话就扩容。然后就真正扩容,使用 grow 方法。
为什么要用减法?因为某些 jvm 的虚拟机中,可能大数组会导致溢出,在距离最大整数值还差 个位数 的时候。
private void ensureExplicitCapacity(int minCapacity) {
modCount++;
// overflow-conscious code
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
MAX_ARRAY_SIZE
最大数组长度。这里规定了是最大整数值 - 8。注释说某些虚拟机对数组会保留一些头部描述,导致OOM,因此规定 -8.
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
grow
扩容到指定容量。扩容的真正实现。
其中 >> 1 是二进制右移,相当于除以 2,所以就是扩容 1.5 倍。
然后赋值一个 新容量的数组给 elementData。
如果这个 新容量,比 MAX_ARRAY_SIZE 大,就会使用 hugeCapacity 方法检查一下是否溢出了。检查方法很简单,看看新容量是否是负数,因为溢出了在二进制里面会变成负数。不信你可以试试把整数最大值+1打印出来看看。
private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;
int newCapacity = oldCapacity + (oldCapacity >> 1);
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);
}
hugeCapacity
这就是检查过程,是负数就抛出异常。
不是的话就返回大小。
private static int hugeCapacity(int minCapacity) {
if (minCapacity < 0) // overflow
throw new OutOfMemoryError();
return (minCapacity > MAX_ARRAY_SIZE) ?
Integer.MAX_VALUE :
MAX_ARRAY_SIZE;
}
size
返回大小
public int size() {
return size;
}
isEmpty
老几样了。
public boolean isEmpty() {
return size == 0;
}
contains
public boolean contains(Object o) {
return indexOf(o) >= 0;
}
indexOf
数组遍历。空的用 == 比较,非空用equals。
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;
}
lastIndexOf
反着遍历
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
克隆。super 是调用的从 Object 继承的 clone 方法,这是一个 native 方法。
这个方法是浅拷贝,意味着基本类型字段会复制值,而引用类型是直接用的引用。因此后面再次创建一个新的数组出来,并且把并发修改记录置 0.
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);
}
}
toArray
转化为数组,这都是继承过来的。前面几期讲过。
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());
System.arraycopy(elementData, 0, a, 0, size);
if (a.length > size)
a[size] = null;
return a;
}
elementData
取数组的元素出来,这是私有方法,不是给外部调用的。
E elementData(int index) {
return (E) elementData[index];
}
get
这是给外部调用的,首先会进行范围检查,上期也讲过,就是检查是不是 小于 size 的数。
public E get(int index) {
rangeCheck(index);
return elementData(index);
}
set
set 会返回旧的数值。
public E set(int index, E element) {
rangeCheck(index);
E oldValue = elementData(index);
elementData[index] = element;
return oldValue;
}
add
之前费了半天劲封装的一大堆扩容派上用场了,无需判断什么时候扩容,只需要把 size + 1 传进去即可。注释写道,这个会使得 modCount 增加。
public boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
在指定位置添加元素。
检查索引合法、检查扩容,然后将 index 位置以及后面的元素往后移动一位,然后把新元素插进去,最后 size++。 arraycopy 也是 native 方法。
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
删除指定位置的元素。 numMoved 检查一下移动多少,试想一下,如果删除的是末尾的元素,则 index = size -1, 最终是不需要进行移动的。最后将末尾置 null 是为了让 垃圾回收器 看到。
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
删除元素。遍历找到索引,然后使用 fastRemove 方法删除。
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;
}
fastRemove
私有方法。这个移除不是用迭代器,而是直接用数组覆盖了。
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
}
clear
清空集合。注意容量并没复原。
public void clear() {
modCount++;
// clear to let GC do its work
for (int i = 0; i < size; i++)
elementData[i] = null;
size = 0;
}
addAll
添加指定集合在末尾。又使用了之前封装的检查扩容方法。然后直接将数组复制过去。
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;
}
removeRange
删除指定范围。套路不变,还是数组内部进行移动,移动完后面置空。
protected void removeRange(int fromIndex, int toIndex) {
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;
}
rangeCheck
检查范围, 大于 size 会数组越界。注释特意说明,为什么不检查小于0,因为底层还是个普通数组,普通数组用负数索引本来就会报错。
private void rangeCheck(int index) {
if (index >= size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
rangeCheckForAdd
对 add 操作的检查索引。这个判断了小于0,并且索引可以等于 size。这个判断小于0是因为 add 操作直接操作数组移动,而不会先进行数组访问。
private void rangeCheckForAdd(int index) {
if (index > size || index < 0)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
outOfBoundsMsg
方便抛异常的方法
private String outOfBoundsMsg(int index) {
return "Index: "+index+", Size: "+size;
}
removeAll
检查非空后批量删除指定集合包含的元素。
public boolean removeAll(Collection<?> c) {
Objects.requireNonNull(c);
return batchRemove(c, false);
}
retainAll
检查非空后批量删除指定集合不包含的元素。
public boolean retainAll(Collection<?> c) {
Objects.requireNonNull(c);
return batchRemove(c, true);
}
batchRemove
批量删除。
使用 r 为读取索引, w 为写入索引。
通过 contains 判断是否符合条件,将符合条件的筛选出来,重新写入到数组内。有点类似于力扣的一道算法题,双指针类型的。
在 finally 模块中进行收尾工作,确保抛出异常数组也是完整的。
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++)
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;
}
writeObject
写入到流中,也就是序列化。
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();
}
}
readObject
反序列化
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();
}
}
}
listIterator
返回指定位置的迭代器,如果不指定位置,就是头部的迭代器
public ListIterator<E> listIterator() {
return new ListItr(0);
}
public ListIterator<E> listIterator(int index) {
if (index < 0 || index > size)
throw new IndexOutOfBoundsException("Index: "+index);
return new ListItr(index);
}
iterator
普通迭代器
public Iterator<E> iterator() {
return new Itr();
}
Itr 类
AbstractList. Itr 的优化版本
private class Itr implements Iterator<E> {
int cursor; // index of next element to return
int lastRet = -1; // index of last element returned; -1 if no such
int expectedModCount = modCount;
Itr() {}
public boolean hasNext() {
return cursor != size;
}
@SuppressWarnings("unchecked")
public E next() {
checkForComodification();
int i = cursor;
if (i >= size)
throw new NoSuchElementException();
Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length)
throw new ConcurrentModificationException();
cursor = i + 1;
return (E) elementData[lastRet = i];
}
public void remove() {
if (lastRet < 0)
throw new IllegalStateException();
checkForComodification();
try {
ArrayList.this.remove(lastRet);
cursor = lastRet;
lastRet = -1;
expectedModCount = modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
@Override
@SuppressWarnings("unchecked")
public void forEachRemaining(Consumer<? super E> consumer) {
Objects.requireNonNull(consumer);
final int size = ArrayList.this.size;
int i = cursor;
if (i >= size) {
return;
}
final Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length) {
throw new ConcurrentModificationException();
}
while (i != size && modCount == expectedModCount) {
consumer.accept((E) elementData[i++]);
}
// update once at end of iteration to reduce heap write traffic
cursor = i;
lastRet = i - 1;
checkForComodification();
}
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}
ListItr 类
AbstractList.ListItr 的优化版本
private class ListItr extends Itr implements ListIterator<E> {
ListItr(int index) {
super();
cursor = index;
}
public boolean hasPrevious() {
return cursor != 0;
}
public int nextIndex() {
return cursor;
}
public int previousIndex() {
return cursor - 1;
}
@SuppressWarnings("unchecked")
public E previous() {
checkForComodification();
int i = cursor - 1;
if (i < 0)
throw new NoSuchElementException();
Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length)
throw new ConcurrentModificationException();
cursor = i;
return (E) elementData[lastRet = i];
}
public void set(E e) {
if (lastRet < 0)
throw new IllegalStateException();
checkForComodification();
try {
ArrayList.this.set(lastRet, e);
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
public void add(E e) {
checkForComodification();
try {
int i = cursor;
ArrayList.this.add(i, e);
cursor = i + 1;
lastRet = -1;
expectedModCount = modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
}
SubList 类
和之前一样,是子列表。通过偏移量来操作子列表。
private class SubList extends AbstractList<E> implements RandomAccess {
private final AbstractList<E> parent;
private final int parentOffset;
private final int offset;
int size;
SubList(AbstractList<E> parent,
int offset, int fromIndex, int toIndex) {
this.parent = parent;
this.parentOffset = fromIndex;
this.offset = offset + fromIndex;
this.size = toIndex - fromIndex;
this.modCount = ArrayList.this.modCount;
}
public E set(int index, E e) {
rangeCheck(index);
checkForComodification();
E oldValue = ArrayList.this.elementData(offset + index);
ArrayList.this.elementData[offset + index] = e;
return oldValue;
}
public E get(int index) {
rangeCheck(index);
checkForComodification();
return ArrayList.this.elementData(offset + index);
}
public int size() {
checkForComodification();
return this.size;
}
public void add(int index, E e) {
rangeCheckForAdd(index);
checkForComodification();
parent.add(parentOffset + index, e);
this.modCount = parent.modCount;
this.size++;
}
public E remove(int index) {
rangeCheck(index);
checkForComodification();
E result = parent.remove(parentOffset + index);
this.modCount = parent.modCount;
this.size--;
return result;
}
protected void removeRange(int fromIndex, int toIndex) {
checkForComodification();
parent.removeRange(parentOffset + fromIndex,
parentOffset + toIndex);
this.modCount = parent.modCount;
this.size -= toIndex - fromIndex;
}
public boolean addAll(Collection<? extends E> c) {
return addAll(this.size, c);
}
public boolean addAll(int index, Collection<? extends E> c) {
rangeCheckForAdd(index);
int cSize = c.size();
if (cSize==0)
return false;
checkForComodification();
parent.addAll(parentOffset + index, c);
this.modCount = parent.modCount;
this.size += cSize;
return true;
}
public Iterator<E> iterator() {
return listIterator();
}
public ListIterator<E> listIterator(final int index) {
checkForComodification();
rangeCheckForAdd(index);
final int offset = this.offset;
return new ListIterator<E>() {
int cursor = index;
int lastRet = -1;
int expectedModCount = ArrayList.this.modCount;
public boolean hasNext() {
return cursor != SubList.this.size;
}
@SuppressWarnings("unchecked")
public E next() {
checkForComodification();
int i = cursor;
if (i >= SubList.this.size)
throw new NoSuchElementException();
Object[] elementData = ArrayList.this.elementData;
if (offset + i >= elementData.length)
throw new ConcurrentModificationException();
cursor = i + 1;
return (E) elementData[offset + (lastRet = i)];
}
public boolean hasPrevious() {
return cursor != 0;
}
@SuppressWarnings("unchecked")
public E previous() {
checkForComodification();
int i = cursor - 1;
if (i < 0)
throw new NoSuchElementException();
Object[] elementData = ArrayList.this.elementData;
if (offset + i >= elementData.length)
throw new ConcurrentModificationException();
cursor = i;
return (E) elementData[offset + (lastRet = i)];
}
@SuppressWarnings("unchecked")
public void forEachRemaining(Consumer<? super E> consumer) {
Objects.requireNonNull(consumer);
final int size = SubList.this.size;
int i = cursor;
if (i >= size) {
return;
}
final Object[] elementData = ArrayList.this.elementData;
if (offset + i >= elementData.length) {
throw new ConcurrentModificationException();
}
while (i != size && modCount == expectedModCount) {
consumer.accept((E) elementData[offset + (i++)]);
}
// update once at end of iteration to reduce heap write traffic
lastRet = cursor = i;
checkForComodification();
}
public int nextIndex() {
return cursor;
}
public int previousIndex() {
return cursor - 1;
}
public void remove() {
if (lastRet < 0)
throw new IllegalStateException();
checkForComodification();
try {
SubList.this.remove(lastRet);
cursor = lastRet;
lastRet = -1;
expectedModCount = ArrayList.this.modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
public void set(E e) {
if (lastRet < 0)
throw new IllegalStateException();
checkForComodification();
try {
ArrayList.this.set(offset + lastRet, e);
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
public void add(E e) {
checkForComodification();
try {
int i = cursor;
SubList.this.add(i, e);
cursor = i + 1;
lastRet = -1;
expectedModCount = ArrayList.this.modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
final void checkForComodification() {
if (expectedModCount != ArrayList.this.modCount)
throw new ConcurrentModificationException();
}
};
}
public List<E> subList(int fromIndex, int toIndex) {
subListRangeCheck(fromIndex, toIndex, size);
return new SubList(this, offset, fromIndex, toIndex);
}
private void rangeCheck(int index) {
if (index < 0 || index >= this.size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
private void rangeCheckForAdd(int index) {
if (index < 0 || index > this.size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
private String outOfBoundsMsg(int index) {
return "Index: "+index+", Size: "+this.size;
}
private void checkForComodification() {
if (ArrayList.this.modCount != this.modCount)
throw new ConcurrentModificationException();
}
public Spliterator<E> spliterator() {
checkForComodification();
return new ArrayListSpliterator<E>(ArrayList.this, offset,
offset + this.size, this.modCount);
}
}
@Override
public void forEach(Consumer<? super E> action) {
Objects.requireNonNull(action);
final int expectedModCount = modCount;
@SuppressWarnings("unchecked")
final E[] elementData = (E[]) this.elementData;
final int size = this.size;
for (int i=0; modCount == expectedModCount && i < size; i++) {
action.accept(elementData[i]);
}
if (modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
}
forEach
Iterable 接口的方法,第一期讲过。
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
先不讲
removeIf
删除符合条件的元素。用一个 BitSet 来记录哪些需要删除。BitSet 是一个里面只有 true 或者 false 的数组。这里面用 true 和 false 记录对应索引的元素是否需要留下。
然后将留下的元素重新赋值回原数组。
BitSet 的 set 方法是将指定索引设置为 true 的意思。
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;
}
replaceAll
通过一个操作器,指定动作,然后将每个元素进行操作后取代原来的元素。比如每个元素都 +1.
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++;
}
sort
调用数组的排序。前面讲过,是一种自适应的排序算法。
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 相比于之前的接口和抽象类,在满足接口规范的同时,比抽象类更加具体,且做出了针对于数组的独特实现和优化。