ArrayList源码解析
- ArrayList是什么?
- 继承结构
- 域
- 构造函数
- 扩容
- 获取大小和判空
- 截断
- 克隆
- 转为数组
- 是否包含元素和获取下标
- 操作集合
- 获取元素
- 设置元素
- 添加元素
- 添加集合
- 删除单个元素
- 删除范围元素
- 求差集和交集
- 全清
- 序列化和反序列化
- 获取迭代器
- 迭代器——Itr内部类
- 迭代器——ListItr内部类
- 获取子串
- 字串——SubList类(以下是类介绍)
- 继承结构
- 域
- 构造函数
- 设置元素
- 获取元素
- 获取大小
- 添加元素
- 删除元素
- 获取迭代器
- 获取子串的子串
- 子串spliterator(子串没有重写forEach,不讲)
- Java8新方法(不讲)
- forEach()
- ArrayListSpliterator()和ArrayListSpliterator类
ArrayList是什么?
ArrayList是基于数组实现的随机访问的List结构,在添加或删除元素时会自动调节ArrayList容量
当需要随机访问,且元素不需要在列表中间进行大量增删操作时,就应该使用ArrayList
继承结构
继承了AbstractList,实现了List,并实现了三个标记接口RandomAccess、Cloneable、Serializable
public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable{
}
域
序列版本号、初始容量、0元素空实例数组缓冲、初始容量空实例数组缓冲、最终数组、实际容量,还有从父类继承的modCount
private static final long serialVersionUID = 8683452581122892189L;
private static final int DEFAULT_CAPACITY = 10;
private static final Object[] EMPTY_ELEMENTDATA = {};
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
transient Object[] elementData;
private int size;
构造函数
- ArrayList()让elementData指向DEFAULTCAPACITY_EMPTY_ELEMENTDATA
ArrayList(int)判断initialCapacity,具体为
- 大于0,elementData指向新数组
- 等于0,elementData指向EMPTY_ELEMENTDATA
- 小于0,抛异常
public ArrayList() {
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
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(Collection<? extends E> c) {
elementData = c.toArray();
if ((size = elementData.length) != 0) {
if (elementData.getClass() != Object[].class)
elementData = Arrays.copyOf(elementData, size, Object[].class);
} else {
this.elementData = EMPTY_ELEMENTDATA;
}
}
ArrayList(Collection)让elementData指向集合转换的数组,让size= elementData.length,判断size
- 不等于0,再判断当前类是否是Object[] (子类可能复写了toArray方法),若不是则转换
- 等于0,elementData指向EMPTY_ELEMENTDATA
扩容
ensureCapacity()供外部扩容,判断elementData是否指向DEFAULTCAPACITY_EMPTY_ELEMENTDATA
- 否,说明不是通过ArrayList()创建,则可能指向EMPTY_ELEMENTDATA或新数组,大于0即扩容
- 是,说明通过ArrayList()创建,其默认大小为10,大于10即扩容
ensureExplicitCapacity()中增加修改次数,判断扩容大小是否大于当前数组大小,大于则调用grow
grow()方法具体为
- 将旧容量按照 oldCapacity + (oldCapacity >> 1) 扩容
- 若新容量小于minCapacity,则新容量为minCapacity
- 若新容量(或minCapacity大于)大于MAX_ARRAY_SIZE,则新容量为hugeCapacity()
- 最后将elementData扩容到新容量
hugeCapacity()具体为
- 判断是否溢出(add方法会传递size+1,若此时size已是Integer.MAX_VALUE则会溢出)
- 若minCapacity > MAX_ARRAY_SIZE,新容量为Integer.MAX_VALUE,否则为MAX_ARRAY_SIZE
public void ensureCapacity(int minCapacity) {
int minExpand = (elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA) ? 0 : DEFAULT_CAPACITY;
if (minCapacity > minExpand) {
ensureExplicitCapacity(minCapacity);
}
}
private void ensureExplicitCapacity(int minCapacity) {
modCount++;
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
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);
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) // overflow
throw new OutOfMemoryError();
return (minCapacity > MAX_ARRAY_SIZE) ? Integer.MAX_VALUE : MAX_ARRAY_SIZE;
}
获取大小和判空
这里返回的是域size,而不是elementData.length(size是实际元素数量,elementData.length是存放元素数组容量)
public int size() {
return size;
}
public boolean isEmpty() {
return size == 0;
}
截断
修改操作次数,将大小截取到size(为0指向EMPTY_ELEMENTDATA),节约空间
public void trimToSize() {
modCount++;
if (size < elementData.length) {
elementData = (size == 0) ? EMPTY_ELEMENTDATA : Arrays.copyOf(elementData, size);
}
}
克隆
clone只是浅拷贝,只拷贝了数组地址,未拷贝里面的元素,即新旧数组会互相影响
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);
}
}
转为数组
- toArray()调用Arrays.copyOf将elementData缩减返回
toArray(T)具体为
- 若a.length < size,则将elementData缩减并转为T[]类型返回
- 若a.length = size,则将elementData从0开始拷贝size个元素到a,返回a
- 若a.length > size,则将elementData从0开始拷贝size个元素到a,a[size]=null,返回a(null后面可能还有元素)
public Object[] toArray() {
return Arrays.copyOf(elementData, size);
}
public <T> T[] toArray(T[] a) {
if (a.length < size)
return (T[]) Arrays.copyOf(elementData, size, a.getClass());
System.arraycopy(elementData, 0, a, 0, size);
if (a.length > size)
a[size] = null;
return a;
}
是否包含元素和获取下标
- contains判断下标是否大于0
- indexOf从头遍历判断元素是否存在,若存在返回下标,不存在返回-1
- lastIndexOf从尾遍历判断元素是否存在,若存在返回下标,不存在返回-1
public boolean contains(Object o) {
return indexOf(o) >= 0;
}
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;
}
操作集合
获取元素
判断是否越界,根据index从数组取出数据并转换类型
- 这里的越界是超出size而不是elementData.length(size < elementData.length)
- 不判断index < 0是因为 elementData[-1]本身就会报错
public E get(int index) {
if (index >= size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
return (E) elementData[index];
}
设置元素
判断是否越界,向对应index设置新元素,取出旧元素返回
- 这里的越界是超出size而不是elementData.length(size < elementData.length)
- 不判断index < 0是因为 elementData[-1]本身就会报错
public E set(int index, E element) {
if (index >= size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index))
E oldValue = (E) elementData[index];
elementData[index] = element;
return oldValue;
}
添加元素
- add(int)调用ensureCapacityInternal,随后将e设置到size++位置
ensureCapacityInternal()供内部扩容,判断elementData是否指向DEFAULTCAPACITY_EMPTY_ELEMENTDATA
- 否,说明不是通过ArrayList()创建,则可能指向EMPTY_ELEMENTDATA或新数组,当size+1到末尾时(0或initialCapacity或c.toArray().length)扩容
- 是,说明通过ArrayList()创建,第一次add()时size+1 = 1 < 10,而10 > elementData.length=0,初始容量为10,但size=1,当size+1到末尾时(10)再次扩容,下一次容量为15
public boolean add(E e) {
ensureCapacityInternal(size + 1);
elementData[size++] = e;
return true;
}
private void ensureCapacityInternal(int minCapacity) {
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
}
ensureExplicitCapacity(minCapacity);
}
public void add(int index, E element) {
if (index > size || index < 0)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
ensureCapacityInternal(size + 1);
System.arraycopy(elementData, index, elementData, index + 1, size - index);
elementData[index] = element;
size++;
}
add(int, E)具体为
- 判断是否溢出(index = size添加末尾,这里判断index < 0保持原子性,避免扩容后再报错导致数据不一致)
- 判断是否扩容和增加修改记录
- System.arraycopy让index后面的元素往后移,空出index
- 在index处赋值,并size++
添加集合
addAll(Collection)将集合转为数组a
- 判断是否扩容和增加修改记录
- 将a从0开始赋值a.length个元素到elementData[size]后面
- size+a.length
- 集合不为空则返回true
public boolean addAll(Collection<? extends E> c) {
Object[] a = c.toArray();
int numNew = a.length;
ensureCapacityInternal(size + numNew);
System.arraycopy(a, 0, elementData, size, numNew);
size += numNew;
return numNew != 0;
}
public boolean addAll(int index, Collection<? extends E> c) {
if (index > size || index < 0)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
Object[] a = c.toArray();
int numNew = a.length;
ensureCapacityInternal(size + numNew);
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;
}
addAll(int, Collection)将集合转为数组a添加到指定位置
- 判断是否溢出(index = size添加末尾,这里判断index < 0保持原子性,避免扩容后再报错导致数据不一致)
- 判断是否扩容和增加修改记录
- 获取index后面元素的个数,若个数大于0(不大于0刚好是最后一个)则后面移动numMoved个位置,空出a.length个位置
- 将数组a填充到index位置
- size+a.length
- 集合不为空则返回true
删除单个元素
remove(int)具体为
- 判断是否溢出(不判断index < 0是因为 elementData[-1]本身就会报错)
- 增加修改次数(为什么不让modCount++位于elementData[index]后面保持原子性?)
- 取出旧元素返回
- 获取index后面元素的个数,若个数大于0(不大于0刚好是最后一个)则后面的依次往前覆盖
- size–,将最后一个元素置为null
public E remove(int index) {
if (index >= size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
modCount++;
E oldValue = (E) elementData[index];
int numMoved = size - index - 1;
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,numMoved);
elementData[--size] = null;
return oldValue;
}
public boolean remove(Object o) {
if (o == null) {
for (int index = 0; index < size; index++)
if (elementData[index] == null) {
fastRemove(index);
return true;
}
} else {
for (int index = 0; index < size; index++)
if (o.equals(elementData[index])) {
fastRemove(index);
return true;
}
}
return false;
}
private void fastRemove(int index) {
modCount++;
int numMoved = size - index - 1;
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,numMoved);
elementData[--size] = null;
}
- remove(Object)循环遍历找到元素下标,调用fastRemove
- fastRemove()增加修改次数,获取index后面元素的个数,若个数大于0(不大于0刚好是最后一个)则后面的依次往前覆盖,size–,将最后一个元素置为null
删除范围元素
- 判断toIndex < fromIndex,其他判断fromIndex < 0、fromIndex >= size()、toIndex > size()交给arraycopy
- 增加修改次数
- 获取toIndex后面元素的个数,将toIndex后面的元素覆盖到fromIndex
- 获取新数组大小
- 将新数组后面的元素置null
protected void removeRange(int fromIndex, int toIndex) {
if (toIndex < fromIndex) {
throw new IndexOutOfBoundsException("toIndex < fromIndex");
}
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;
}
求差集和交集
求差集(complement=false)具体为
- 若elementData[r])在集合c中不存在,则将elementData[r]保存到 elementData[w++]位置(即覆盖前面存在的元素)
- 若c.contains()抛异常(c可能是Collection子类并复写了contains方法,故可能异常)则将r后续元素拼接到w后,让w加上后续元素数量
- 若遍历完后若w != size(只有元素全部不相等才可能w==size)则将w后面置null,记录置空次数,w为新size,返回true
public boolean removeAll(Collection<?> c) {
Objects.requireNonNull(c);
return batchRemove(c, false);
}
public boolean retainAll(Collection<?> c) {
Objects.requireNonNull(c);
return batchRemove(c, true);
}
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 {
if (r != size) {
System.arraycopy(elementData, r,elementData, w,size - r);
w += size - r;
}
if (w != size) {
for (int i = w; i < size; i++)
elementData[i] = null;
modCount += size - w;
size = w;
modified = true;
}
}
return modified;
}
求交集(complement=true)具体为
- 若elementData[r])在集合c中存在,则将elementData[r]保存到 elementData[w++]位置(即覆盖前面不存在的元素)
- 若c.contains()抛异常(c可能是Collection子类并复写了contains方法,故可能异常)则将r后续元素拼接到w后,让w加上r后续元素的数量
- 若遍历完后若w != size(只有元素全部相等才可能w==size)则将w后面置null,记录置空次数,w为新size,返回true
全清
增加修改次数,遍历将元素置为null,size为0
public void clear() {
modCount++;
for (int i = 0; i < size; i++)
elementData[i] = null;
size = 0;
}
序列化和反序列化
- writeObject将当前对象、size和元素写到ObjectOutputStream
- readObject则将当前对象、size和元素读到ObjectInputStream
private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException{
int expectedModCount = modCount;
s.defaultWriteObject();
s.writeInt(size);
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;
s.defaultReadObject();
s.readInt();
if (size > 0) {
ensureCapacityInternal(size);
Object[] a = elementData;
for (int i=0; i<size; i++) {
a[i] = s.readObject();
}
}
}
获取迭代器
- iterator()返回从实现Iterator的迭代器Itr
- listIterator()返回实现ListIterator且位置为0的迭代器ListItr
- listIterator(final int index)返回指定位置的迭代器ListItr
public Iterator<E> iterator() {
return new Itr();
}
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);
}
迭代器——Itr内部类
- 域limit存储size,避免在迭代过程中并发修改从而改变size导致hasNext()的值不确定(andoird代码)
- hasNext()判断游标是否小于limit
- forEachRemaining()不讲
next()可连续调用,调用前可不用hasNext(),具体为
- 先判断集合是否已被并发修改
- 再判断游标是否已到元素末尾(避免连续调用next)
- 再判断是否已到数组末尾(避免elementData被并发缩减)
- 根据游标取出元素(用i保持原子性,避免cursor被修改)
- 将游标加1,记录越过的元素位置
private class Itr implements Iterator<E> {
protected int limit = ArrayList.this.size;
int cursor;
int lastRet = -1;
int expectedModCount = modCount;
public boolean hasNext() {
return cursor < limit;
}
public E next() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
int i = cursor;
if (i >= limit)
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 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++]);
}
cursor = i;
lastRet = i - 1;
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
public void remove() {
if (lastRet < 0)
throw new IllegalStateException();
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
try {
ArrayList.this.remove(lastRet);
cursor = lastRet;
lastRet = -1;
expectedModCount = modCount;
limit--;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
}
remove()具体为
- 先判断是否调用了next()
- 再判断是否已被并发修改
- 调用外部类的remove()移除上一个越过的元素(remove报错则一定发生了并发修改)
- 删除后数组移动,游标回退到所移动元素的左边
- lastRet = -1避免连续调用remove()
- 记录修改次数,大小减1
迭代器——ListItr内部类
ListItr 继承了 Itr(向后遍历) 且实现了 ListIterator(向前遍历)
- 构造函数获取指定位置的迭代器(从头开始则为0)
- hasPrevious()判断当前是否到了位置0
- nextIndex()和previousIndex()返回当前游标和上一个游标
previous()具体为
- 先判断集合是否已被并发修改
- 再判断是否到元素开头(避免连续调用previous)
- 再判断是否已到数组末尾(避免elementData被并发缩减)
- 根据游标取出元素(用i保持原子性,避免cursor被修改)
- 将游标减1,记录越过的元素位置
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;
}
public E previous() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
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();
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
try {
ArrayList.this.set(lastRet, e);
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
public void add(E e) {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
try {
int i = cursor;
ArrayList.this.add(i, e);
cursor = i + 1;
lastRet = -1;
expectedModCount = modCount;
limit++;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
}
set()具体为
- 先判断是否调用了next()或previous()
- 再判断是否已被并发修改
- 调用外部类的set覆盖上一个越过的元素(set报错则一定发生了并发修改)
- (未lastRet = -1,说明可重复set,覆盖上一个)
- 记录修改次数
add()具体为
- 先判断是否已被并发修改
- 用外部类的add()在游标处添加元素(用i保持原子性,避免add时cursor被修改,数组越界说明集合被并发缩减)
- lastRet = -1避免调用set()、remove(),但可连续调用add()
- 游标加1,记录修改次数,大小加1
获取子串
subList判断传入范围是否合法,随后创建SubList返回
public List<E> subList(int fromIndex, int toIndex) {
subListRangeCheck(fromIndex, toIndex, size);
return new SubList(this, 0, fromIndex, toIndex);
}
static void subListRangeCheck(int fromIndex, int toIndex, int size) {
if (fromIndex < 0)
throw new IndexOutOfBoundsException("fromIndex = " + fromIndex);
if (toIndex > size)
throw new IndexOutOfBoundsException("toIndex = " + toIndex);
if (fromIndex > toIndex)
throw new IllegalArgumentException("fromIndex(" + fromIndex + ") > toIndex(" + toIndex + ")");
}
字串——SubList类(以下是类介绍)
继承结构
采用组合模式继承AbstractList,RandomAccess的子串也是RandomAccess
private class SubList extends AbstractList<E> implements RandomAccess {
}
域
parent指向父串,parentOffset为父串开始截取的index,offset为两个index之差,此外还有一个从父串继承的modCount
private final AbstractList<E> parent;
private final int parentOffset;
private final int offset;
int size;
构造函数
在subList()已经对index判断了,这里不再需要判断
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;
}
设置元素
判断下标是否合法,判断是否并发修改,后给ArrayList的elementData赋值(加上子串的偏移量),返回旧元素
public E set(int index, E e) {
if (index < 0 || index >= this.size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
if (ArrayList.this.modCount != this.modCount)
throw new ConcurrentModificationException();
E oldValue = (E) ArrayList.this.elementData[offset + index];
ArrayList.this.elementData[offset + index] = e;
return oldValue;
}
获取元素
判断下标是否合法,判断是否并发修改,后从ArrayList的elementData取值(加上子串的偏移量)
public E get(int index) {
if (index < 0 || index >= this.size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
if (ArrayList.this.modCount != this.modCount)
throw new ConcurrentModificationException();
return (E) ArrayList.this.elementData[offset + index];
}
获取大小
检查是否并发修改,后返回size(为两个index之差)
public int size() {
if (ArrayList.this.modCount != this.modCount)
throw new ConcurrentModificationException();
return this.size;
}
添加元素
- add()检查是否越界、并发修改,后调用ArrayList.add方法(加上子串的偏移量),同步修改次数,size+1
- addAll(Collection)添加集合到数组末尾
- addAll(int, Collection)检查是否越界、c.size是否为0、并发修改,后调用ArrayList.addAll方法(加上子串的偏移量),同步修改次数,size+c.size
public void add(int index, E e) {
if (index < 0 || index > this.size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
if (ArrayList.this.modCount != this.modCount)
throw new ConcurrentModificationException();
parent.add(parentOffset + index, e);
this.modCount = parent.modCount;
this.size++;
}
public boolean addAll(Collection<? extends E> c) {
return addAll(this.size, c);
}
public boolean addAll(int index, Collection<? extends E> c) {
if (index < 0 || index > this.size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
int cSize = c.size();
if (cSize==0)
return false;
if (ArrayList.this.modCount != this.modCount)
throw new ConcurrentModificationException();
parent.addAll(parentOffset + index, c);
this.modCount = parent.modCount;
this.size += cSize;
return true;
}
删除元素
- remove检查是否越界、并发修改,后调用ArrayList.remove方法(加上子串的偏移量),同步修改次数,size-1
- removeRange检查并发修改,后调用ArrayList.removeRange方法(加上子串的偏移量),同步记修次数,size-(toIndex-fromIndex)
public E remove(int index) {
if (index < 0 || index >= this.size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
if (ArrayList.this.modCount != this.modCount)
throw new ConcurrentModificationException();
E result = parent.remove(parentOffset + index);
this.modCount = parent.modCount;
this.size--;
return result;
}
protected void removeRange(int fromIndex, int toIndex) {
if (ArrayList.this.modCount != this.modCount)
throw new ConcurrentModificationException();
parent.removeRange(parentOffset + fromIndex,parentOffset + toIndex);
this.modCount = parent.modCount;
this.size -= toIndex - fromIndex;
}
获取迭代器
- iterator()调用AbstractList.ListIterator()再调用AbstractList.listIterator(0),利用多态实际调用Sublist.listIterator(0)
listIterator(int)返回指定位置的listIterator(其为SubList类的匿名内部类),下面为介绍
- 检查并发修改和是否越界
- hasNext()和hasPrevious()判断是否到开头末尾
- nextIndex()和previousIndex()返回当前游标和上一个游标
next()同上面的ltr.next(),但加上了子串偏移量,可连续调用,调用前可不用hasNext(),具体为
- 判断并发修改、是否到元素末尾(避免连续调用next)、是否到数组末尾(避免elementData被并发缩减)
- 根据游标取出元素(用i保持原子性,避免cursor被修改),将游标加1,记录越过的元素位置
previous()同上面的ListItr.previous(),但加上了子串偏移量,可连续调用,调用前可不用hasPrevious(),具体为
- 判断并发修改、是否到元素末尾(避免连续调用previous)、是否到数组末尾(避免elementData被并发缩减)
- 根据游标取出元素(用i保持原子性,避免cursor被修改),将游标减1,记录越过的元素位置
public Iterator<E> iterator() {
return listIterator();
}
public ListIterator<E> listIterator(final int index) {
if (ArrayList.this.modCount != this.modCount)
throw new ConcurrentModificationException();
if (index < 0 || index > this.size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(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;
}
public boolean hasPrevious() {
return cursor != 0;
}
public int nextIndex() {
return cursor;
}
public int previousIndex() {
return cursor - 1;
}
public E next() {
if (expectedModCount != ArrayList.this.modCount)
throw new ConcurrentModificationException();
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 E previous() {
if (expectedModCount != ArrayList.this.modCount)
throw new ConcurrentModificationException();
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)];
}
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++)]);
}
lastRet = cursor = i;
if (expectedModCount != ArrayList.this.modCount)
throw new ConcurrentModificationException();
}
public void remove() {
if (lastRet < 0)
throw new IllegalStateException();
if (expectedModCount != ArrayList.this.modCount)
throw new ConcurrentModificationException();
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();
if (expectedModCount != ArrayList.this.modCount)
throw new ConcurrentModificationException();
try {
ArrayList.this.set(offset + lastRet, e);
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
public void add(E e) {
if (expectedModCount != ArrayList.this.modCount)
throw new ConcurrentModificationException();
try {
int i = cursor;
SubList.this.add(i, e);
cursor = i + 1;
lastRet = -1;
expectedModCount = ArrayList.this.modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
};
}
remove()具体为
- 判断是否调用了next()或previous()、是否并发修改
- 调用SubList.remove()移除上一个越过的元素(remove报错则一定发生了并发修改)
- 删除后数组移动,游标回退到所移动元素的左边,lastRet = -1避免连续调用remove(),记录修改次数
set()具体为
- 判断是否调用了next()或previous()、是否并发修改
- 调用SubList.set()覆盖上一个越过的元素(加上偏移量,set报错则一定发生了并发修改)
- (未lastRet = -1,说明可重复set,覆盖上一个),记录修改次数
add()具体为
- 判断是否并发修改
- 用外部类的add()在游标处添加元素(用i保持原子性,避免add时cursor被修改,数组越界说明集合被并发缩减)
- lastRet = -1避免调用set()、remove(),但可连续调用add(), 游标加1,记录修改次数
获取子串的子串
subList()调用自身的构造方法,将自己截断
public List<E> subList(int fromIndex, int toIndex) {
subListRangeCheck(fromIndex, toIndex, size);
return new SubList(this, offset, fromIndex, toIndex);
}
——————————————————————————
子串spliterator(子串没有重写forEach,不讲)
public Spliterator<E> spliterator() {
if (modCount != ArrayList.this.modCount)
throw new ConcurrentModificationException();
return new ArrayListSpliterator<E>(ArrayList.this, offset,offset + this.size, this.modCount);
}
Java8新方法(不讲)
forEach()
public void forEach(Consumer<? super E> action) {
Objects.requireNonNull(action);
final int expectedModCount = modCount;
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();
}
}
ArrayListSpliterator()和ArrayListSpliterator类
public Spliterator<E> spliterator() {
return new ArrayListSpliterator<>(this, 0, -1, 0);
}
static final class ArrayListSpliterator<E> implements Spliterator<E> {
private final ArrayList<E> list;
private int index;
private int fence;
private int expectedModCount;
ArrayListSpliterator(ArrayList<E> list, int origin, int fence,int expectedModCount) {
this.list = list;
this.index = origin;
this.fence = fence;
this.expectedModCount = expectedModCount;
}
private int getFence() {
int hi;
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 ArrayListSpliterator<E> trySplit() {
int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
return (lo >= mid) ? null :
new ArrayListSpliterator<E>(list, lo, index = mid,expectedModCount);
}
public boolean tryAdvance(Consumer<? super E> action) {
if (action == null)
throw new NullPointerException();
int hi = getFence(), i = index;
if (i < hi) {
index = i + 1;
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;
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.SUBS
}
}
@Override
public boolean removeIf(Predicate<? super E> filter) {
Objects.requireNonNull(filter);
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++) {
final E element = (E) elementData[i];
if (filter.test(element)) {
removeSet.set(i);
removeCount++;
}
}
if (modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
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;
}
this.size = newSize;
if (modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
modCount++;
}
return anyToRemove;
}
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++;
}
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++;
}