写在前言
ArrayList的本质是由数组进行实现的,默认数组长度为10,也可手动指定数组长度或者去掉未使用的空间,除了提供对数组的增删改查、扩容、数组集合转换、批量增加、批量删除、范围删除、IO流序列化/反序列化、排序、按条件删除、循环按条件处理、按条件删除、替代等方法外,还包含了ArrayListSpliterator分割集合、listIterator迭代、SubList截取等类
清单列表
属性
DEFAULT_CAPACITY:默认数组长度、常量(10)。
EMPTY_ELEMENTDATA:空数组、常量。
DEFAULTCAPACITY_EMPTY_ELEMENTDATA:默认数组,在初始化扩容的时候数组长度不会低于默认数组长度、常量。
elementData:存储元素数组,transient修饰,不能被序列化,防止未使用空间写入。
size:数组实际长度,不包含未使用空间。
MAX_ARRAY_SIZE:要分配数组的最大大小,一些虚拟机在数组中保存一些头字,分配更大的数组会报OutOfMemoryError错误,内存溢出。
构造方法
ArrayList(int initialCapacity):initialCapacity > 0按参数长度初始化elementData,initialCapacity = 0空数组无长度初始化elementData。
ArrayList():将默认数组初始化elementData。
ArrayList(Collection<? extends E> c):先将集合转换成数组赋值给elementData,数组长度等于0赋值EMPTY_ELEMENTDATA,数组长度大于0,验证数组的类型,如果不是Object类型进行对元素转换。
公有方法
trimToSize():去掉未使用的数组空间。
ensureCapacity(int minCapacity):公有扩容方法,如果要增加大量元素,使用这个方法可以一次性增加,防止多次扩容,降低效率。
size():返回实际长度。
isEmpty():判断数组是否有元素。
contains(Object o):判断是否包含元素。
indexOf(Object o):返回元素第一个下标。
lastIndexOf(Object o):返回元素最后一个下标。
clone():数组拷贝方法,数组长度、数组、操作数置0.
toArray():集合转数组。
toArray(T[] a):集合按参数类型转数组。
get(int index):公有方法:获取下标的元素。
set(int index, E element):给下标的元素重新赋值。
add(E e):添加原素。
add(int index, E element):在下标处添加元素。
remove(int index):删除元素。
remove(Object o):删除第一个等于参数的元素。
clear():清空数组。
addAll(Collection c):将集合转换成数组进行扩容添加。
addAll(int index, Collection c):在下标处进行添加集合转换后的数组。
removeAll(Collection c):删除包含集合的元素。
retainAll(Collection<?> c):删除不包含集合的元素。
forEach(Consumer<? super E> action):循环执行accept处理。
removeIf(Predicate<? super E> filter):删除符合filter的元素。
replaceAll(UnaryOperator operator):循环将元素按operator进行替换。
sort(Comparator<? super E> c):对集合进行排序。
私有方法
ensureCapacityInternal(int minCapacity):私有扩容方法。
ensureExplicitCapacity(int minCapacity):扩容前置,进行操作计数和长度判断。
grow(int minCapacity):扩容方法。
hugeCapacity(int minCapacity):长度大于最大大小扩容处理长度方法。
fastRemove(int index):删除下标元素的方法。
rangeCheck(int index):验证数组下标越界。
rangeCheckForAdd(int index):验证数组下标越界。
outOfBoundsMsg(int index):输出数组的信息。
batchRemove(Collection<?> c, boolean complement):removeAll,retainAll调用的删除方法,区别是complement。
writeObject(java.io.ObjectOutputStream s):数组序列化。(ArrayList list = new ArrayList(); ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file)); oos.writeObject(list); )
readObject(java.io.ObjectInputStream s):数组反序列化。
default方法
elementData(int index):默认方法,取下标的元素。
protected方法
removeRange(int fromIndex, int toIndex):删除范围内的元素,包含开始元素,不包含结束元素。
内部类
Itr类:迭代器。
ListItr类:继承Itr类,并对其进行了升级。
SubList类:可以截取源集合的视图,但不能操作源集合,不然会报异常。
ArrayListSpliterator类:基于索引二分法拆分数组。
源码
/**
* 默认数组长度,常量
*/
private static final int DEFAULT_CAPACITY = 10;
/**
* 空数组,常量
*/
private static final Object[] EMPTY_ELEMENTDATA = {};
/**
* 赋值默认长度的数组,常量
*/
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
/**
* 实际数组,变量
*/
transient Object[] elementData; // non-private to simplify nested class access
/**
* 实际长度,变量
*/
private int size;
/**
* 带参长度的构造函数,大于0将new一个该长度的数组赋值实际数组,等于0就把常量空数组赋值实际数组,小于0抛出数字不合法异常
*/
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;
}
/**
* 传参集合,先将集合转换成数组,赋值给实际数组,判断数组长度是不是等于0,等于0将常量空数组赋值实际数组,否则,判断数组的类型是不是等于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);
}
}
/**
* 用于外部调用,如果要增加大量元素,使用这个方法可以一次性增加,防止多次扩容,降低效率
*/
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);
}
}
/**
* 内部方法,判断如果是默认数组,给默认长度10,并和传参长度取最大值进入下个方法扩容
*/
private void ensureCapacityInternal(int minCapacity) {
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
}
ensureExplicitCapacity(minCapacity);
}
/**
* 扩容方法前置,操作计数,如果要扩容的长度大于数组长度就执行扩容方法
*/
private void ensureExplicitCapacity(int minCapacity) {
modCount++;
// overflow-conscious code
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
/**
* 要分配数组的最大大小,一些虚拟机在数组中保存一些头字,分配更大的数组会报OutOfMemoryError错误,内存溢出。
*/
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
/**
* 首先扩容1.5倍,如果扩完之后小于传参长度,就直接赋予传参长度,如果该长度大于最大数组长度,就要进行处理是赋予定义大小还是数组最大大小,增加操作数组的长度
*/
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);
}
/**
* 如果传参长度小于0,报内存溢出错误,否则,如果传参长度大于最大长度,给最大长度,否则给定义去除头字的长度
*/
private static int hugeCapacity(int minCapacity) {
if (minCapacity < 0) // overflow
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;
}
/**
* 判断是否包含某个元素
*/
public boolean contains(Object o) {
return indexOf(o) >= 0;
}
/**
* 进行空和有值判断,拿取第一个下标返回,没有返回-1
*/
public int indexOf(Object o) {
if (o == null) {
for (int i = 0; i < size; i++)
if (elementData[i]==null)
return i;
} else {
for (int i = 0; i < size; i++)
if (o.equals(elementData[i]))
return i;
}
return -1;
}
/**
* 进行空和有值判断,拿取最后一个下标返回,没有返回-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;
}
/**
* 拷贝当前数组的基础属性操作数、实际长度等,深度拷贝实际数组,将操作数置为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);
}
}
/**
* 将集合转为数组返回,这种是OBJECT的,如果转换类型要一个个转换
*/
public Object[] toArray() {
return Arrays.copyOf(elementData, size);
}
/**
* 将集合转换成数组返回,可以返回固定数组类型的
*/
@SuppressWarnings("unchecked")
public <T> T[] toArray(T[] a) {
if (a.length < size)
// Make a new array of a's runtime type, but my contents:
return (T[]) Arrays.copyOf(elementData, size, a.getClass());
System.arraycopy(elementData, 0, a, 0, size);
if (a.length > size)
// 将最后一个置空,因为最大下标=长度-1
a[size] = null;
return a;
}
// Positional Access Operations
/**
* 内部方法,用来获取目的下标的值
*/
@SuppressWarnings("unchecked")
E elementData(int index) {
return (E) elementData[index];
}
/**
* 获取固定下标的值
*/
public E get(int index) {
rangeCheck(index);
return elementData(index);
}
/**
* 更新固定下标的值为参数值,并返回旧值
*/
public E set(int index, E element) {
rangeCheck(index);
E oldValue = elementData(index);
elementData[index] = element;
return oldValue;
}
/**
* 增加一个元素为参数值,先扩容,再赋值
*/
public boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
/**
* 在目的下标处增加一个元素为参数值
*/
public void add(int index, E element) {
rangeCheckForAdd(index);
ensureCapacityInternal(size + 1); // Increments modCount!!
System.arraycopy(elementData, index, elementData, index + 1,
size - index);
elementData[index] = element;
size++;
}
/**
* 删除目的下标处的值
*/
public E remove(int index) {
rangeCheck(index);
modCount++;
E oldValue = elementData(index);
int numMoved = size - index - 1;
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
elementData[--size] = null; // clear to let GC do its work
return oldValue;
}
/**
* 删除数组中等于参数的元素,只删除第一个
*/
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; // clear to let GC do its work
}
/**
* 清空集合,操作计数,实际数组每个设置成null,实际长度设置成0
*/
public void clear() {
modCount++;
// clear to let GC do its work
for (int i = 0; i < size; i++)
elementData[i] = null;
size = 0;
}
/**
* 将集合添加进当前集合中,从最后一个元素开始添加
*/
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;
}
/**
* 范围删除,删除从开始下标到结束下标的值
*/
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;
}
/**
*判断传入参数index是不是大于实际长度,如果大于等于,抛出数组下标越界异常。
*/
private void rangeCheck(int index) {
if (index >= size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
/**
* 断下标如果大于实际长度或者下标小于0,抛出数组下标越界异常,并将size+1。
*/
private void rangeCheckForAdd(int index) {
if (index > size || index < 0)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
/**
* 返回return "Index: "+index+", Size: "+size;下标和实际长度。
*/
private String outOfBoundsMsg(int index) {
return "Index: "+index+", Size: "+size;
}
/**
* 方法判断集合是否为空,返回 return batchRemove(c, false);方法
*
* @param c collection containing elements to be removed from this list
* @return {@code true} if this list changed as a result of the call
* @throws ClassCastException if the class of an element of this list
* is incompatible with the specified collection
* (<a href="Collection.html#optional-restrictions">optional</a>)
* @throws NullPointerException if this list contains a null element and the
* specified collection does not permit null elements
* (<a href="Collection.html#optional-restrictions">optional</a>),
* or if the specified collection is null
* @see Collection#contains(Object)
*/
public boolean removeAll(Collection<?> c) {
Objects.requireNonNull(c);
return batchRemove(c, false);
}
/**
*方法判断集合是否为空,返回 return batchRemove(c, true);方法。
*
* @param c collection containing elements to be retained in this list
* @return {@code true} if this list changed as a result of the call
* @throws ClassCastException if the class of an element of this list
* is incompatible with the specified collection
* (<a href="Collection.html#optional-restrictions">optional</a>)
* @throws NullPointerException if this list contains a null element and the
* specified collection does not permit null elements
* (<a href="Collection.html#optional-restrictions">optional</a>),
* or if the specified collection is null
* @see Collection#contains(Object)
*/
public boolean retainAll(Collection<?> c) {
Objects.requireNonNull(c);
return batchRemove(c, true);
}
/**
* 使用final定义一个新数组,将缓冲区数组赋值给新数组,定义两个变量r、w等于0,
* 定义修改状态为false,try遍历实际长度,使用变量r作为下标,如果集合c包含定义常量的某一个值,并等于参数布尔状态,将定义常量的下标w++赋值缓冲区数组下标r,
* (当布尔状态为false的时候,将所有参数集合和新数组不交集的值放至最前面,当布尔状态为false的时候,将所有参数集合和新数组交集的值放至最前面),finally最终处理
* 防止contains异常,如果r!=size,深拷贝将w后的数据拷贝到新数组,将w+=size - r;如果w != size,遍历实际长度,将大于w的下标的值都设成null,并将操作次数+size-w次,
* 将w赋值给最新长度,并标记修改状态为true,返回修改状态。
* @param c
* @param complement
* @return
*/
private boolean batchRemove(Collection<?> c, boolean complement) {
final Object[] elementData = this.elementData;
int r = 0, w = 0;
boolean modified = false;
try {
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;
}
/**
* 方法定义的抛出IO输入输出异常,首先定义常数操作次数,
* 然后调用IO的defaultWriteObject方法将除了transient的其它数据序列化,再将数组大小序列化,
* 然后再把元素一个个的序列化,如果操作次数不等于常数,抛出在排序期间有进行修改数组的异常。
*
* @serialData The length of the array backing the <tt>ArrayList</tt>
* instance is emitted (int), followed by all of its elements
* (each an <tt>Object</tt>) in the proper order.
*/
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();
}
}
/**
* 参数传入IO流的ObjectInputStream,方法定义的抛出IO异常、类找不到异常,首先定义缓冲区数组为空数组(1),
* 将除了transient的其它数据反序列化,再将数组长度反序列化,如果实际长度大于0,调用ensureCapacityInternal(size);对数组进行扩容,
* 定义一个常数数组,将缓冲区数组赋值给常数数组,循环实际长度,给每个下标赋值a[i] = s.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
ensureCapacityInternal(size);
Object[] a = elementData;
// Read in all elements in the proper order.
for (int i=0; i<size; i++) {
a[i] = s.readObject();
}
}
}
/**
* 如果下标小于0或者下标大于实际长度的时候,抛出数组下标越界异常,返回对象return new ListItr(index);。
*
* <p>The returned list iterator is <a href="#fail-fast"><i>fail-fast</i></a>.
*
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
public ListIterator<E> listIterator(int index) {
if (index < 0 || index > size)
throw new IndexOutOfBoundsException("Index: "+index);
return new ListItr(index);
}
/**
* 返回对象return new ListItr(0);。
*
* <p>The returned list iterator is <a href="#fail-fast"><i>fail-fast</i></a>.
*
* @see #listIterator(int)
*/
public ListIterator<E> listIterator() {
return new ListItr(0);
}
/**
* 返回对象return new Itr();。
*
* <p>The returned iterator is <a href="#fail-fast"><i>fail-fast</i></a>.
*
* @return an iterator over the elements in this list in proper sequence
*/
public Iterator<E> iterator() {
return new Itr();
}
/**
* An optimized version of AbstractList.Itr
*/
private class Itr implements Iterator<E> {
int cursor; // 定义下一个要访问的元素下标
int lastRet = -1; // 定义上一个要访问的元素下标
int expectedModCount = modCount; // 定义常数接收操作次数
public boolean hasNext() {
return cursor != size;
}
@SuppressWarnings("unchecked")
public E next() {
checkForComodification();
int i = cursor;
if (i >= size)
throw new NoSuchElementException();
Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length)
throw new ConcurrentModificationException();
cursor = i + 1;
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();
}
}
/**
* An optimized version of 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();
}
}
}
/**
* 调用subListRangeCheck(fromIndex, toIndex, size);方法检查,返回对象new SubList(this, 0, fromIndex, toIndex);。
*
* @throws IndexOutOfBoundsException {@inheritDoc}
* @throws IllegalArgumentException {@inheritDoc}
*/
public List<E> subList(int fromIndex, int toIndex) {
subListRangeCheck(fromIndex, toIndex, size);
return new SubList(this, 0, fromIndex, toIndex);
}
/**
* 如果开始下标小于0,抛出数组下标越界异常,如果结束下标大于实际长度,抛出数组下标越界异常,如果开始下标大于结束下标,抛出数据不合法异常。
* @param fromIndex
* @param toIndex
* @param size
*/
static void subListRangeCheck(int fromIndex, int toIndex, int size) {
if (fromIndex < 0)
throw new IndexOutOfBoundsException("fromIndex = " + fromIndex);
if (toIndex > size)
throw new IndexOutOfBoundsException("toIndex = " + toIndex);
if (fromIndex > toIndex)
throw new IllegalArgumentException("fromIndex(" + fromIndex +
") > toIndex(" + toIndex + ")");
}
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);
}
}
/**
* 首先检测集合是否存在,定义常数操作数等于操作数,定义一个数组等于缓冲区数组,
* 定义一个变量等于实际长度,循环实际长度,并且操作数正确,将常数数组接收,如果操作数不相等,抛出数组修改操作数异常。
* @param 参数为consumer类型,传参进去无返回值按照穿进去的方法进行处理
*/
@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();
}
}
/**
* 返回对象return new ArrayListSpliterator<>(this, 0, -1, 0);。
*
* @return a {@code Spliterator} over the elements in this list
* @since 1.8
*/
@Override
public Spliterator<E> spliterator() {
return new ArrayListSpliterator<>(this, 0, -1, 0);
}
/** Index-based split-by-two, lazily initialized Spliterator */
static final class ArrayListSpliterator<E> implements Spliterator<E> {
/**
属性:分割集合、当前下标、结束下标、操作数
*/
private final ArrayList<E> list;
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(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)
ArrayList<E> lst;
if ((hi = fence) < 0) {
if ((lst = list) == null)
hi = fence = 0;
else {
expectedModCount = lst.modCount;
hi = fence = lst.size;
}
}
return hi;
}
// 分割list,返回一个返回一个新分割出的spilterator实例,二分法
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);
}
// 返回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
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;
}
}
/**
* 检测集合是否存在,定义删除总数量变量等于0,定义删除数据BitSet集合。定义常数操作数等于操作数,定义长度等于实际长度,
* 遍历循环实际长度,如果操作数正确,定义一个元素接收缓冲区数组下标的值,如果检验参数有这个元素,将这个元素的下标放入删除集合,删除个数+1,如果操作次数不相符,
* 抛出操作次数异常,定义布尔常数等于删除个数大于0,如果这个布尔参数为真,定义新的长度等于实际长度减去要删除的个数,循环新长度并且实际长度,
* 将缓冲区数组的值进行修改,将多余的遍历为null,将新长度赋值给实际长度,如果操作次数有异常抛出异常,无就将操作次数加1,并且返回布尔状态。
* @param 传参Predicate(处理方法,lamda表达式),传参返回布尔值
* @return
*/
@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;
}
/**
* 首先使用Objects.requireNonNull(operator);判断集合是否为空,定义一个常数等于操作次数,
* 定义一个常数等于实际长度,遍历循环常数实际长度,判断条件常数操作次数与操作次数相等,以防替换数据的时候有进行修改,
* 将数据进行替换elementData[i] = operator.apply((E) elementData[i]);,如果常数操作次数不等于操作次数,抛出数组有修改异常,无异常将操作次数进行加1。
* @param 传什么类型的参数返回什么值,参数里面是执行方法(例:list.replaceAll(a->a.equals("zhangsan")?"张三":a);)
*/
@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++;
}
/**
* 定义一个常数等于操作次数,调用Arrays.sort((E[]) elementData, 0, size, c);方法进行排序,如果操作次数不等于常数,抛出在排序期间有进行修改数组的异常,无异常抛出就将操作次数。
* @param c
*/
@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++;
}