目录
简介
ArrayList位置java.util包下面,是List集合的一种,底层是动态数组,它的容量能够动态的增长。ArrayList是非同步的,只能在单线程中使用。
ArrayList继承AbstractList抽象类,并且实现List接口,提供了操作元素的方法;实现了RandomAccess接口,支持快速随机访问,通过索引可以访问元素;实现了Cloneable接口,能被克隆;实现了java.io.Serializable接口,支持序列化,并能进行序列化传输。
ArrayList擅长访问元素,但是插入和移除元素比较慢。
ArrayList介绍(基于jdk1.8)
1.构造方法
public ArrayList(Collection<? extends E> c){}
public ArrayList() {}
public ArrayList(int initialCapacity){}
- 构建一个包含了集合c的元素的ArrayList。
- 无参构造函数,构建一个容量为10的ArrayList(官方解释),在jdk1.8中默认是空实例,在调用add()/addAll()方法时会进行扩容。
- 构造一个指定容量大小的ArrayList。
2.内部变量
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;
- DEFAULT_CAPACITY----默认的容器大小。
- DEFAULTCAPACITY_EMPTY_ELEMENTDATA与EMPTY_ELEMENTDATA相比,在添加第一个元素后确定扩容多大。
- elementData----ArrayList的底层数组缓冲。
- size----ArrayList中元素的总数。
3.内部方法
public void trimToSize(){}
public void ensureCapacity(int minCapacity) {}
public int size() {}
public boolean isEmpty() {}
public boolean contains(Object o) {}
public int indexOf(Object o) {}
public int lastIndexOf(Object o) {}
public Object clone() {}
public Object[] toArray() {}
public <T> T[] toArray(T[] a) {}
public E get(int index) {}
public E set(int index, E element) {}
public boolean add(E e) {}
public void add(int index, E element) {}
public E remove(int index) {}
public boolean remove(Object o) {}
public void clear() {}
public boolean addAll(Collection<? extends E> c) {}
public boolean addAll(int index, Collection<? extends E> c) {}
public boolean removeAll(Collection<?> c) {}
public boolean retainAll(Collection<?> c) {}
public ListIterator<E> listIterator(int index) {}
public ListIterator<E> listIterator() {}
public Iterator<E> iterator() {}
public List<E> subList(int fromIndex, int toIndex) {}
public void forEach(Consumer<? super E> action) {}
public Spliterator<E> spliterator() {}
public boolean removeIf(Predicate<? super E> filter) {}
public void replaceAll(UnaryOperator<E> operator) {}
public void sort(Comparator<? super E> c) {}
- trimToSize()----将ArrayList的实际容量调整为实际元素总数大小。
- ensureCapacity()----如有必要,ArrayList需要扩容,以容纳minCapacity个元素个数。
- size()---返回ArrayList中元素总数。
- isEmpty()----如果ArrayList中没有任何元素,则返回true。
- contains(Object o)----如果ArrayList中包含指定的元素o,返回true。
- indexOf(Object o)----返回ArrayList中首次出现指定元素的索引,如果不包含指定元素,返回-1。
- lastIndexOf(Object o)----返回ArrayList中最后出现指定元素的索引,如果不包含指定元素,返回-1。
- clone()----返回ArrayList实例的浅度复制。
- toArray()----按合适的顺序(第一个到最后一个元素)返回包含ArrayList中所有元素的数组。
- toArray(T[] a)----按合适的顺序(第一个到最后一个元素)返回包含ArrayList中所有元素的数组,返回数组的运行类型是指定的数组类型。
- get(int index)----获取ArrayList中指定索引位置的元素。
- set(int index,E element)----用指定的元素替换ArrayList指定索引的元素。
- add(E e)----将指定的元素添加到ArrayList的尾部。
- add(int index, E element)----将指定元素添加到ArrayList指定的元素。
- remove(int index)----移除ArrayList中指定索引的元素。
- remove(Object o )----移除ArrayList中首次出现的指定元素。
- clear()---清空ArrayList中所有元素。
- add(Collection<? extends E> c)----将集合c中的所有元素添加到ArrayList中。
- addAll(int index, Collection<? extends E> c)----将集合c中所有元素添加到ArrayList中,位置从index开始。
- removeAll(Collection<?> c)----从ArrayList中移除包含在集合c中的所有元素。
- retainAll(Collection<?> c)----包留ArrayList中包含在集合c中的元素,即请求ArrayList和集合c的交集。
- listIterator(int index)----返回ArrayList中指定位置开始的所有元素的迭代器。
- listIterator()----返回ArrayList中所有元素的迭代器ListIterator。
- iterator()----返回ArrayList中所有元素的迭代器Iterator。
- subList(int fromIndex, int toIndex)----返回ArrayList中fromIndex开始(包含)到toIndex(不包含)之间所有元素。
- forEach(Consumer<? super E> action)----jdk1.8,对ArrayList中所有元素执行指定action操作。
- removeIf(Predicate<? super E> filter)-----jdk1.8,用于移除符合指定条件的元素。
- replaceAll(UnaryOperator<E> operator)----对每个元素执行operator指定的操作,并用操作结果来替换原来的元素。
- sort(Comparator<? super E> c)----将ArrayList中所元素按照指定规则进行排序。
源码分析
关于源码的几点说明:
1)ArrayList底层是数组缓冲elementData,向ArrayList添加元素会判断是否需要扩容,elementData被transient关键字修饰,无法序列化(被static修饰的字段也无法序列化),ArrayList序列化是将元素长度和所有元素写到流中。
2)modCount在源码中多次出现,用来记录修改次数,由于ArrayList是非线程安全的,任何对ArrayList的修改都会增加。迭代器迭代初始化时会赋值给 expectedModCount。在迭代过程中,会判断 modCount是否等于 expectedModCount,如果不等,说明其他线程修改了ArrayList,就会抛出ConcurrentModificationException异常。
3)最大扩容到Integer.MAX_VALUE - 8是由于预留出位置用于保存数组元信息(指针指向类信息,描述对象类型)。
4)注意elementData.length与size的区别,elementData是底层数组的容量大小,size是数组中元素的总数。
5)类似操作subList(fromIndex,toIndex),包含了索引fromIndex,其范围是0-(size-1),而toIndex是不包含,其范围是0-size。
所以toIndex>=fromIndex,当toIndex==fromIndex时,表示不做任何的操作。
6)elementData[--size],数组的下标是0开始,所以最后一个元素索引是size-1,--size操作表示size本身自减1,然后再使用size。
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;
//用于空实例的共享空数组实例
private static final Object[] EMPTY_ELEMENTDATA = {};
//默认大小的空实例共享的空数组实例,与EMPTY_ELEMENTDATA的区分开以便在添加第一个元素后确定扩容多大
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
//elementData是ArrayList存储元素的数组缓冲,ArrayList的容量是数组缓冲长度,
//任何elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA的空ArrayList会在添加第一个元素后扩容到DEFAULT_CAPACITY=10。
//由于被transient修饰,无法序列化(被static修改的字段也无法序列化)
transient Object[] elementData; // non-private to simplify nested class access
//ArrayList的大小(即包含元素的数量)
private int size;
//构造一个指定初始容量的ArrayList
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);
}
}
//构造一个初始容量为10的空ArrayList(官方解释),实际会在添加第一个元素后会才进行扩容
public ArrayList() {
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
//构造一个包含了指定collection的元素的ArrayList,与collection的迭代器返回的顺序是一样的
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;
}
}
//缩减ArrayList的容量到当前实际元素总数大小
public void trimToSize() {
//modCount用来记录修改次数,由于ArrayList是非线程安全的,任何对ArrayList的修改都会增加modCount的值,
//迭代器迭代初始化时会赋值给 expectedModCount。在迭代过程中,会判断 modCount是否等于 expectedModCount,
//如果不等,说明其他线程修改了ArrayList,就会抛出ConcurrentModificationException异常
modCount++;
if (size < elementData.length) {
elementData = (size == 0)
? EMPTY_ELEMENTDATA
: Arrays.copyOf(elementData, size);
}
}
//扩充ArrayList的容量,如有必要保证其容量至少能存储指定的minCapacity个元素
public void ensureCapacity(int minCapacity) {
//这里判断是ArrayList容量是否是默认的,如果是不是默认的需要扩容
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);
}
}
private static int calculateCapacity(Object[] elementData, int minCapacity) {
//DEFAULTCAPACITY_EMPTY_ELEMENTDATA是无参构造函数创建的,初次添加元素会扩容到默认大小(10)
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
return Math.max(DEFAULT_CAPACITY, minCapacity);
}
//如果有参数构造函数,在原先的容量上扩容minCapacity
return minCapacity;
}
//在add()/addAll()方法调用的时候,进行扩容
private void ensureCapacityInternal(int minCapacity) {
ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
}
private void ensureExplicitCapacity(int minCapacity) {
modCount++;
// overflow-conscious code
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
//预留出位置用于保存数组的元信息(指针指向类信息,描述对象类型)
//https://stackoverflow.com/questions/35756277/why-the-maximum-array-size-of-arraylist-is-integer-max-value-8
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;
//oldCapacity右移1位,即oldCapacity/2,所以新容量是旧容量的1.5倍
int newCapacity = oldCapacity + (oldCapacity >> 1);
//新容量小于最小需求容量,则新容量应该是最小需求容量
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;
//新容量大于最大扩容容量情况,如果需要扩容的容量大于了最大数组容量,最大也只能到int范围最大值
if (newCapacity - MAX_ARRAY_SIZE > 0)
newCapacity = hugeCapacity(minCapacity);
// minCapacity is usually close to size, so this is a win:
//复制数组,容量为newCapacity
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;
}
//返回ArrayList中的元素个数
public int size() {
return size;
}
//如果ArrayList中不包含任何元素,返回true.
public boolean isEmpty() {
return size == 0;
}
//如果ArrayList中包含指定的元素,返回true
public boolean contains(Object o) {
return indexOf(o) >= 0;
}
//返回ArrayList中首次出现指定元素的索引,如果不包含元素,返回-1.
public int indexOf(Object o) {
if (o == null) {
//如果为null的时候,遍历数组,找到第一个null对应的索引
for (int i = 0; i < size; i++)
if (elementData[i]==null)
return i;
} else {
//如果不为null的情况下,遍历数组,找到符合要求的第一个元素对应索引
for (int i = 0; i < size; i++)
if (o.equals(elementData[i]))
return i;
}
//找不到对应的元素,返回-1
return -1;
}
//返回ArrayList中最后出现指定元素的索引,如果不包含元素,返回-1
public int lastIndexOf(Object o) {
if (o == null) {
//如果为null,逆向遍历,找到第一个null,返回对应索引
for (int i = size-1; i >= 0; i--)
if (elementData[i]==null)
return i;
} else {
//如果不为null的情况下,逆向遍历,找到符合要求的第一个元素对应索引
for (int i = size-1; i >= 0; i--)
if (o.equals(elementData[i]))
return i;
}
//找不到对应的元素,返回-1
return -1;
}
//返回ArrayList实例的浅度复制
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);
}
}
//按适当的顺序返回(从第一个到最后一个元素)包含ArrayList中所有元素的数组
public Object[] toArray() {
//数组的大小是size,而不是length
return Arrays.copyOf(elementData, size);
}
//按适当的顺序返回(从第一个到最后一个元素)包含ArrayList中所有元素的数组
//并且返回数组的运行类型是指定的数组类型
public <T> T[] toArray(T[] a) {
//会判断a的长度与集合当前size
//a的长度小于size时,复制elementData副本,转换对应类型
if (a.length < size)
// Make a new array of a's runtime type, but my contents:
return (T[]) Arrays.copyOf(elementData, size, a.getClass());
//a的长度大于等于size时,将elementDate元素直接复制到a中
System.arraycopy(elementData, 0, a, 0, size);
//将数组中大于size位置置为null
if (a.length > size)
a[size] = null;
return a;
}
// Positional Access Operations
//返回数组中指定索引位置上的元素
@SuppressWarnings("unchecked")
E elementData(int index) {
return (E) elementData[index];
}
//返回ArrayList中指定索引的元素
public E get(int index) {
//检查索引index范围
rangeCheck(index);
return elementData(index);
}
//用指定的元素替换ArrayList中指定索引的元素
public E set(int index, E element) {
//检查索引index范围
rangeCheck(index);
//根据索引获取原先值
E oldValue = elementData(index);
//用element替换原先位置上的值
elementData[index] = element;
return oldValue;
}
//将指定的元素添加到ArrayList的尾部
public boolean add(E e) {
//扩容
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
//将指定的元素添加到ArrayList指定的位置
public void add(int index, E element) {
//检查索引的范围
rangeCheckForAdd(index);
ensureCapacityInternal(size + 1); // Increments modCount!!
//将index索引后整体向后移动一个位置
System.arraycopy(elementData, index, elementData, index + 1,
size - index);
elementData[index] = element;
size++;
}
//移除ArrayList中指定位置的元素
public E remove(int index) {
//检查索引的位置
rangeCheck(index);
modCount++;
//获取指定索引位置的值
E oldValue = elementData(index);
//删除index位置,需要将index+1----size之间的元素整体前移一个位置
//所以总共移动的元素个数=size-(index+1)=numMoved
int numMoved = size - index - 1;
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
//ArrayList中总元素数是size,索引从0开始,最后一个元素的索引是size-1
//--size同时实现size的自减
elementData[--size] = null; // clear to let GC do its work
return oldValue;
}
//移除ArrayList中首次出现的指定元素
public boolean remove(Object o) {
if (o == null) {
//为空的情况下,找到首次出现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 remove method that skips bounds checking and does not
* return the value removed.
*/
private void fastRemove(int index) {
modCount++;
//需要移除的元素索引是index,需要将index+1----size之间位置元素整体前移
//需要移动的元素总数是size-(index+1);
int numMoved = size - index - 1;
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
//ArrayList中总元素数是size,索引从0开始,最后一个元素的索引是size-1
elementData[--size] = null; // clear to let GC do its work
}
//从ArrayList中移除所有的元素
public void clear() {
modCount++;
// clear to let GC do its work
//遍历集合,将所有索引位置置为null
for (int i = 0; i < size; i++)
elementData[i] = null;
size = 0;
}
//将集合c中元素添加到ArrayList的末尾,按照c迭代器返回的顺序。
public boolean addAll(Collection<? extends E> c) {
Object[] a = c.toArray();
int numNew = a.length;
//扩容
ensureCapacityInternal(size + numNew); // Increments modCount
//将集合c中元素复制到elementData的末尾,长度是集合c的长度
System.arraycopy(a, 0, elementData, size, numNew);
size += numNew;
return numNew != 0;
}
//将集合c中所有元素添加到ArrayList中,位置从指定的index开始。
public boolean addAll(int index, Collection<? extends E> c) {
//检查索引的范围
rangeCheckForAdd(index);
Object[] a = c.toArray();
int numNew = a.length;
//扩容
ensureCapacityInternal(size + numNew); // Increments modCount
//计算列表中index开始元素个数
int numMoved = size - index;
if (numMoved > 0)
//将ArrayList中index开始的元素总数向后移动numNew个位置,为了向list中添加集合c所有元素
System.arraycopy(elementData, index, elementData, index + numNew,
numMoved);
System.arraycopy(a, 0, elementData, index, numNew);
size += numNew;
return numNew != 0;
}
//移除ArrayList中从fromIndex索引(包含)开始到toIndex(不包含)之间的所有元素
protected void removeRange(int fromIndex, int toIndex) {
modCount++;
//list中从toIndex索引开始的元素整体移动到fromIndex索引开始,个数toIndex之后的元素总数
int numMoved = size - toIndex;
System.arraycopy(elementData, toIndex, elementData, fromIndex,
numMoved);
// clear to let GC do its work
//list之前元素总数减去删除元素总数
int newSize = size - (toIndex-fromIndex);
for (int i = newSize; i < size; i++) {
//将多出的位置置为null
elementData[i] = null;
}
size = newSize;
}
//检查索引范围,超出size,索引越界
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));
}
//索引越界异常打印的消息
private String outOfBoundsMsg(int index) {
return "Index: "+index+", Size: "+size;
}
//从ArrayList中移除所有包含在指定集合c中的元素
public boolean removeAll(Collection<?> c) {
Objects.requireNonNull(c);
return batchRemove(c, false);
}
//ArrayList中只保留指定集合c中包含的元素,即移除ArrayList中不包含了指定集合c中元素
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 {
//当complement=true时,elementData中所有包含在集合c中的元素被保留
//当complement=false时,elementData中所有不包含在集合c中的元素被保留
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.
//按道理for循环中最后r++肯定会等于size,r!=size表示可能发生异常
if (r != size) {
System.arraycopy(elementData, r,
elementData, w,
size - r);
w += size - r;
}
//w是保留元素最后一个索引值,for循环中最后会进行w++操作,如果size==w,表明所有元素保留,返回false
//w!=size表明w后面索引位置现在没有元素,但之前的elementData中w后面位置后元素存在,需要将这些位置置为null
if (w != size) {
// clear to let GC do its work
for (int i = w; i < size; i++)
elementData[i] = null;
modCount += size - w;
size = w;
modified = true;
}
}
return modified;
}
//将arrayList中容量以及所元素写到流中
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();
}
}
//重新构建ArrayList实例,先读取数组的容量,在读取所有的元素
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();
}
}
}
//返回ArrayList中指定位置开始所有元素的迭代器
public ListIterator<E> listIterator(int index) {
if (index < 0 || index > size)
throw new IndexOutOfBoundsException("Index: "+index);
return new ListItr(index);
}
//返回ArrayList所有元素的迭代器(以合适的顺序)
public ListIterator<E> listIterator() {
return new ListItr(0);
}
//返回ArrayList中所有元素的迭代器(以合适的顺序)
public Iterator<E> iterator() {
return new 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向前移动
cursor = i + 1;
//返回elementData中索引为i的元素
return (E) elementData[lastRet = i];
}
public void remove() {
if (lastRet < 0)
throw new IllegalStateException();
//检查是否并发
checkForComodification();
try {
//调用ArrayList中remove()方法移除元素
//lastRet在next()中进行赋值为i
ArrayList.this.remove(lastRet);
cursor = lastRet;
lastRet = -1;
expectedModCount = modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
//循环数组
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();
}
}
//内部类,专门用于list集合遍历ListIterator()迭代器
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();
//i为游标向前移动一位
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();
}
}
}
//返回ArrayList中索引fromIndex(包含)到toIndex(不包含)之间的所有的元素(部分视图)
public List<E> subList(int fromIndex, int toIndex) {
//检查索引的范围
subListRangeCheck(fromIndex, toIndex, size);
return new SubList(this, 0, fromIndex, toIndex);
}
//对ArrayList中的所有元素执行的指定的action操作
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();
}
}
@Override
//移除符合指定条件filter的元素
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后面,第一个为false的索引
i = removeSet.nextClearBit(i);
elementData[j] = elementData[i];
}
//总共移除元素removeCount,需要将size-removeCout之后索引位置置为null
for (int k=newSize; k < size; k++) {
elementData[k] = null; // Let gc do its work
}
this.size = newSize;
if (modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
modCount++;
}
return anyToRemove;
}
//将ArrayList进行排序,会调用Arrays.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++;
}
}
案例
public void test11() {
List<Integer> list = new ArrayList<>(Arrays.asList(1,2,3,4,5));
list.add(6);
System.out.println(list);
//迭代器遍历元素
ListIterator<Integer> iter = list.listIterator();
while(iter.hasNext()) {
System.out.print(iter.next()+",");
}
System.out.println();
//对于list中所有元素执行后面的操作
list.forEach(li->System.out.print(li+","));
System.out.println();
//移除符合条件的元素
list.removeIf(li->li.intValue()%2==1);
System.out.println(list);
//sort()方法,升序
list.sort(new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
if(o1>o2) {
return 1;
}else if(o1<o2) {
return -1;
}else {
return 0;
}
}
});
System.out.println(list);
//sort()方法,降序
list.sort((x,y)->Integer.compare(y, x));
System.out.println(list);
}