标签:
package java.util;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.function.UnaryOperator;
/**
* 可以改变大小的List的实现,实现所有的List的操作,允许保存各种元素,包括null。除了实现
* List接口之外,这个类提供了操作内部存储数据的数组大小的方法。(这个类相当于Vector,
* 但是它并不是线程同步的,不是线程安全的)
*
* size,isEmpty,set,iterator,listIterator方法运行时间为常量时间,add方法运行为摊还常量
* 时间,也即增加n个元素的时间为O(n)。其他的操作运行时间大致为线性时间,常数因子相较
* 于LinkedList更小
*
* 每个ArrayList实例都有一个容量,是存储数据的数组的大小,他至少是List的元素数量的大小。
* 随着元素的增加,容量自动增加。容量增大的细节在添加一个元素有恒定的时间成本摊销的基础上
*
* 在添加大量元素前,应用程序可以使用ensureCapacity方法增大Arraylist的容量, 这可能减少
* 增量重新分配的次数
*
* 这个实现是非线程安全的,如果有多个线程同时操作一个ArrayList实例,其中至少有一个线程
* 在修改这个实例的结构,则必须在外部使用同步控制(一个结构上的修改操作指的是添加或删除一个
* 或多个元素,或者明确改变存储数据的数组大小,仅仅改变元素值不是结构上的修改),这一般由
* 封装ArrayList的类来进行。
*
* 如果没有这样的对象存在,列表应该使用Collections.synchronizedList方法来获得同步的
* (线程安全的)装饰对象(代理对象)。这个操作最好在创建的时候进行,来防止意外的非同步的
* 操作。还可以使用concurrent包下的CopyOnWriteArrayList代替ArrayList的使用
*
*
* 使用类的iterator()和listIterator(int)方法会出发fail-fast错误机制(抛出
* ConcurrentModificationException异常),如果创建了iterator后进行结构上的修改,除了使
* 用iterator的remove或者add方法。因此,在并发修改时,iterator快速失败并且清除,而不是冒
* 着将来可能发生的不确定的风险。
*
* 迭代器的fail-fast错误机制不能被保证,通常来说,很难保证在非同步并发修改操作的fail-fast
* 机制。fail-fast错误机制的迭代器力所能及的抛出ConcurrentModificationException。
* 所以,开发时不应该依赖这个异常保证程序的正确性,仅仅在发现bug时使用
* 继承了AbstractList,可以继承部分默认的实现
* 实现了Cloneable, java.io.Serializable,允许克隆和序列化
*/
publicclassArrayList<E>extendsAbstractList<E>
implementsList<E>,RandomAccess,Cloneable, java.io.Serializable
{
//序列号
privatestaticfinallong serialVersionUID =8683452581122892189L;
/**
* 列表默认容量
*/
privatestaticfinalint DEFAULT_CAPACITY =10;
/**
* 共享空数组实例,用于空实例。调用构造函数容量为0时,会赋予数据的数组
*/
privatestaticfinalObject[] EMPTY_ELEMENTDATA ={};
/**
* 共享空数组实例用于默认大小的空实例。使用默认构造函数时,会赋予数据的数组
*/
privatestaticfinalObject[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA ={};
/**
* 存储数据的数组,数组大小就是列表的容量的大小。在第一次加入元素时,任何空实例
* (DEFAULTCAPACITY_EMPTY_ELEMENTDATA)会扩充成默认大小。
* transient表示序列化过程不希望被序列化的字段,ArrayList自己实现的序列化机制会
* 逐个序列化每个元素
*/
transientObject[] elementData;// non-private to simplify nested class access
/**
* 列表中元素的数量
*
* @serial
*/
privateint size;
/**
* 构造一个指定容量的空列表
*
* @param initialCapacity 列表的初始容量
* @throws IllegalArgumentException 传入的初始容量为负数时,抛出次异常
*/
publicArrayList(int initialCapacity){
if(initialCapacity >0){
this.elementData =newObject[initialCapacity];
}elseif(initialCapacity ==0){
this.elementData = EMPTY_ELEMENTDATA;
}else{
thrownewIllegalArgumentException("Illegal Capacity: "+
initialCapacity);
}
}
/**
* 构造一个默认大小的空列表
*/
publicArrayList(){
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
/**
* 根据传入的集合,构造一个列表,元素的顺序是传入集合的迭代器返回的顺序
*
* @param c 传入的容器
* @throws NullPointerException 传入的容器为空时抛出异常
*/
publicArrayList(Collection<?extends E> c){
elementData = c.toArray();
if((size = elementData.length)!=0){
// c.toArray()可能没有返回 Object[]
if(elementData.getClass()!=Object[].class)
//转成Object类型
elementData =Arrays.copyOf(elementData, size,Object[].class);
}else{
// 如果传入的集合没有元素,则使用空数组代替
this.elementData = EMPTY_ELEMENTDATA;
}
}
/**
* 减小列表的容器大小至列表中元素数量
*/
publicvoid trimToSize(){
modCount++;
if(size < elementData.length){
elementData =(size ==0)
? EMPTY_ELEMENTDATA
:Arrays.copyOf(elementData, size);
}
}
/**
* 增大ArrayList实例的容量, 如果必要,保证能够存储传入的最小容量个元素
*
* @param minCapacity 需要的最少的存储容量
*/
publicvoid 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);
}
}
privatevoid ensureCapacityInternal(int minCapacity){
//默认大小数组,将数组扩展成默认或者minCapacity的大的容量
if(elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA){
minCapacity =Math.max(DEFAULT_CAPACITY, minCapacity);
}
ensureExplicitCapacity(minCapacity);
}
//确保数组能够保存足够的元素
privatevoid ensureExplicitCapacity(int minCapacity){
modCount++;
// 当要求的数量大于数组的大小,扩充成需要的数量
if(minCapacity - elementData.length >0)
grow(minCapacity);
}
/**
* 最大允许的容量
* 一些虚拟机会存储一些头信息
* 尝试分配大容量的数组会导致OutOfMemoryError,超出虚拟机的限制
*/
privatestaticfinalint MAX_ARRAY_SIZE =Integer.MAX_VALUE -8;
/**
* 扩充容量以保证能够存储需要的容量(传入的参数)
*
* @param minCapacity 需要的容量大小
*/
privatevoid grow(int minCapacity){
// overflow-conscious code
int oldCapacity = elementData.length;
//扩充原来容量的1/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:
elementData =Arrays.copyOf(elementData, newCapacity);
}
// 根据需要的容量大小,获得超大容量
privatestaticint hugeCapacity(int minCapacity){
if(minCapacity <0)// 如果minCapacity小于0,则超出最大整数值
thrownewOutOfMemoryError();
return(minCapacity > MAX_ARRAY_SIZE)?
Integer.MAX_VALUE :
MAX_ARRAY_SIZE;
}
/**
* 返回列表的中元素的数量
*
* @return 列表的中元素的数量
*/
publicint size(){
return size;
}
/**
* 判断列表是否为空
*
* @return 当列表中没有元素则返回true,否则返回false
*/
publicboolean isEmpty(){
return size ==0;
}
/**
* 当列表中存在传入的元素,返回true。进一步,列表中至少有一个传入的元素,则返回true
* 比如 o为null,则判断列表中是否有null元素,返回o与列表中的元素e的equals()比较的结果
*
* @param 需要检验是否在列表中的元素的对象
* @return 如果列表中存在o则返回true
*/
publicboolean contains(Object o){
return indexOf(o)>=0;
}
/**
* 返回列表中第一次出现的o(equals方法返回true)的索引,如果不存在则返回-1
*/
publicint 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;
}
/**
* 返回列表中最后一次出现的o(equals方法返回true)的索引,如果不存在则返回-1
*/
publicint 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;
}
/**
* 返回ArrayList实例的浅表复制,不复制列表的元素(都指向相同的对象,没有创建新的对
* 象)。
*/
publicObject 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
thrownewInternalError(e);
}
}
/**
* 获得按照列表顺序存储的数组,这个方法需要分配内存存储拷贝的数组。(浅复制)
*
* @return an array containing all of the elements in this list in
* proper sequence
*/
publicObject[] toArray(){
returnArrays.copyOf(elementData, size);
}
/**
* 获得按照列表顺序存储的数组,返回一个泛型数组,这个方法需要分配内存存储拷贝的数组
* (浅复制),返回的数组的类型应该是参数指定的类型。如果传入的数组大小大于列表的元素
* 则返回,传入的数组,否则创建一个新的数组,并返回新创建的数组
*
* 如果传入的数组长度大于列表的长度,则设置其第size个元素为null(当且仅当在知道list中
* 没有null元素时,用于判断list中元素个数)
* @param a 如果足够大,存储列表中的元素,否则根据传入的运行时参数创建一个新的数组
* @return 返回列表元素的一个拷贝
* @throws ArrayStoreException if the runtime type of the specified array
* is not a supertype of the runtime type of every element in
* this list
* @throws NullPointerException if the specified array is null
*/
@SuppressWarnings("unchecked")
public<T> T[] toArray(T[] a){
if(a.length < size)
// Make a new array of a‘s runtime type, but my contents:
return(T[])Arrays.copyOf(elementData, size, a.getClass());
System.arraycopy(elementData,0, a,0, size);
if(a.length > size)
a[size]=null;
return a;
}
/**
* 根据索引,获得列表中第index个元素,首先检查下标是否在正确的范围
*/
@SuppressWarnings("unchecked")
E elementData(int index){
return(E) elementData[index];
}
/**
* 返回第index个元素
*
* @param index index of the element to return
* @return the element at the specified position in this list
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
public E get(int index){
rangeCheck(index);
return elementData(index);
}
/**
* 将第index个元素的值修改为传入的元素值,首先检查下标是否在正确的范围,返回修改前的值
*
* @param index 元素的索引
* @param element 设置到index的值
* @return 原来位于index的值
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
public E set(int index, E element){
rangeCheck(index);
E oldValue = elementData(index);
elementData[index]= element;
return oldValue;
}
/**
* 在列表的末尾添加元素,修改列表的元素数量(size)。首先需要确保列表的容量足够存放新
* 添加的元素。
*
* @param e element to be appended to this list
* @return <tt>true</tt> (as specified by {@link Collection#add})
*/
publicboolean add(E e){
ensureCapacityInternal(size +1);// 确保能够存放添加元素,容量不足则扩容
elementData[size++]= e;
returntrue;
}
/**
* 在列表第index个位置插入一个元素,index及其后面的元素向后移动一个位置,然后将需要插
* 入的值存入第index的位置
*
* @param index index at which the specified element is to be inserted
* @param element element to be inserted
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
publicvoid add(int index, E element){
rangeCheckForAdd(index);
ensureCapacityInternal(size +1);// 确保有足够的存储空间
System.arraycopy(elementData, index, elementData, index +1,
size - index);
elementData[index]= element;
size++;
}
/**
* 移除列表中第index个元素,index后面的元素向前移动一个位置,列表元素数量减小1
*
* @param index 移除的元素的下标
* @return 返回被删除的元素
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
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;// 释放,以让垃圾回收器回收
return oldValue;
}
/**
* 移除列表中第一个o(o为null时,第一个null元素,否则,是第一个equals()为true的元
* 素),如果过不存在,则不改变。如果列表中存在这样的元素,则返回true,否则返回false
*
* @param o element to be removed from this list, if present
* @return <tt>true</tt> if this list contained the specified element
*/
publicboolean remove(Object o){
if(o ==null){
for(int index =0; index < size; index++)
if(elementData[index]==null){
fastRemove(index);
returntrue;
}
}else{
for(int index =0; index < size; index++)
if(o.equals(elementData[index])){
fastRemove(index);
returntrue;
}
}
returnfalse;
}
/*
* 快速移除元素,不检查索引范围,不返回被删除元素
*/
privatevoid fastRemove(int index){
modCount++;
int numMoved = size - index -1;
if(numMoved >0)
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
elementData[--size]=null;// 释放,以让垃圾回收器回收
}
/**
* 移除列表中所有的元素,操作后,列表为空
*/
publicvoid clear(){
modCount++;
// 释放所有引用,以让垃圾收集器回收
for(int i =0; i < size; i++)
elementData[i]=null;
//列表大小改为0
size =0;
}
/**
* 向列表末尾添加c中的所有元素,顺序是c.iterator()返回的顺序,添加了元素返回true。
*
* @param c collection containing elements to be added to this list
* @return <tt>true</tt> if this list changed as a result of the call
* @throws NullPointerException if the specified collection is null
*/
publicboolean 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;
}
/**
* 向列表第index位置起添加c中的所有元素,顺序是c.iterator()返回的顺序,index及其后面
* 的元素向后移动c中元素个位置,添加了元素返回true。首先需要检查index是否是在范围内
*
* @param index index at which to insert the first element from the
* specified collection
* @param c collection containing elements to be added to this list
* @return <tt>true</tt> if this list changed as a result of the call
* @throws IndexOutOfBoundsException {@inheritDoc}
* @throws NullPointerException if the specified collection is null
*/
publicboolean 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;
}
/**
* 移除元素,移除[fromIndex,toIndex)范围的元素,不包括toIndex
*
* @throws IndexOutOfBoundsException if {@code fromIndex} or
* {@code toIndex} is out of range
* ({@code fromIndex < 0 ||
* fromIndex >= size() ||
* toIndex > size() ||
* toIndex < fromIndex})
*/
protectedvoid removeRange(int fromIndex,int toIndex){
modCount++;
int numMoved = size - toIndex;
System.arraycopy(elementData, toIndex, elementData, fromIndex,
numMoved);
// 释放(移动后列表最后一个元素之后的)引用,以让垃圾收集器回收
int newSize = size -(toIndex-fromIndex);
for(int i = newSize; i < size; i++){
elementData[i]=null;
}
size = newSize;
}
/**
* 检查索引值是否在合理的范围内,不在则抛出异常
* negative: It is always used immediately prior to an array access,
* which throws an ArrayIndexOutOfBoundsException if index is negative.
*/
privatevoid rangeCheck(int index){
if(index >= size)
thrownewIndexOutOfBoundsException(outOfBoundsMsg(index));
}
/**
* 检查索引值是否在合理的范围内,不在则抛出异常
*/
privatevoid rangeCheckForAdd(int index){
if(index > size || index <0)
thrownewIndexOutOfBoundsException(outOfBoundsMsg(index));
}
/**
* 生成数组越界异常信息
*/
privateString outOfBoundsMsg(int index){
return"Index: "+index+", Size: "+size;
}
/**
* 移除列表中的c中包含的所有元素
*
* @param c 需要移除的元素集合,不能为空
* @return 如果列表改变了,则返回true,否则返回false
* @throws ClassCastException 如果传入的集合中有与列表中元素类型不匹配时,抛出该异
* 常
* @throws NullPointerException ArrayList不支持null,但c中包含null元素时,抛出该
* 异常
*/
publicboolean removeAll(Collection<?> c){
Objects.requireNonNull(c);
return batchRemove(c,false);
}
/**
* 保留列表中与c中共有的元素(求交集)。
*
* @param c 需要完成交集的集合,不允许为空
* @return 如果列表改变了,则返回true,否则返回false
* @throws ClassCastException 如果传入的集合中有与列表中元素类型不匹配时,抛出该异
* 常
* @throws NullPointerException ArrayList不支持null,但c中包含null元素时,抛出该
* 异常
*/
publicboolean retainAll(Collection<?> c){
Objects.requireNonNull(c);
return batchRemove(c,true);
}
/**
* 批量删除, complement为true时,保留与c中相同的元素,否则,保留与c中不相同的元素
*/
privateboolean batchRemove(Collection<?> c,boolean complement){
finalObject[] 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{
//保护动作,当c.contains()抛出异常时,将剩余的(r之后的)元素保留
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;
}
/**
* 将一个ArrayList实例的状态保存到流中,也即序列化,这是类实现的序列化机制,不是默认
* 的序列化机制
*
* @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.
*/
privatevoid writeObject(java.io.ObjectOutputStream s)
throws java.io.IOException{
// Write out element count, and any hidden stuff
int expectedModCount = modCount;
s.defaultWriteObject();//默认序列化,记录列表中元素的个数
// 将列表大小作为容量保存,以此适用于clone()
s.writeInt(size);
// 按照正确顺序保存列表中的元素
for(int i=0; i<size; i++){
s.writeObject(elementData[i]);
}
//序列化过程中是否有修改列表的结构(扩容,添加,移除操作)
//如果有,则抛出ConcurrentModificationException异常
if(modCount != expectedModCount){
thrownewConcurrentModificationException();
}
}
/**
* 从流中读取并重新创建Arraylist,也即反序列化
*/
privatevoid readObject(java.io.ObjectInputStream s)
throws java.io.IOException,ClassNotFoundException{
elementData = EMPTY_ELEMENTDATA;
// Read in size, and any hidden stuff
s.defaultReadObject();//默认反序列化,读取列表元素个数
// 读取容量,忽略
s.readInt();// ignored
if(size >0){
// 类似于clone(),创建大小与元素个数相同的数组
ensureCapacityInternal(size);
Object[] a = elementData;
// 以正确的顺序读取所有的元素
for(int i=0; i<size; i++){
a[i]= s.readObject();
}
}
}
/**
* 创建一个从index开始的ListIterator(第一次调用next,返回index处的元素),调用
* previous,则返回index-1处的元素,首先检查index的正确性
*
* The returned list iterator is fail-fast
*
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
publicListIterator<E> listIterator(int index){
if(index <0|| index > size)
thrownewIndexOutOfBoundsException("Index: "+index);
returnnewListItr(index);
}
/**
* 重载,创建一个默认从0开始的ListIterator
*
* The returned list iterator is fail-fast
*
* @see #listIterator(int)
*/
publicListIterator<E> listIterator(){
returnnewListItr(0);
}
/**
* 按照正确的顺序,产生一个iterator
*
* @return an iterator over the elements in this list in proper sequence
*/
publicIterator<E> iterator(){
returnnewItr();
}
/**
* AbstractList.Itr的优化
*/
privateclassItrimplementsIterator<E>{
int cursor;// 下一个元素的游标(索引)
int lastRet =-1;// 上一次返回的元素的索引
int expectedModCount = modCount;
//是否存在下一个,没有遍历到末尾,返回true
publicboolean hasNext(){
return cursor != size;
}
//返回下一个元素
@SuppressWarnings("unchecked")
public E next(){
//检查迭代器过程中,是否有修改ArrayList的实例的结构
//有则抛出ConcurrentModificationException异常
checkForComodification();
int i = cursor;
if(i >= size)
thrownewNoSuchElementException();//超出size范围,则抛出异常
Object[] elementData =ArrayList.this.elementData;
if(i >= elementData.length)
thrownewConcurrentModificationException();
cursor = i +1;//记录下一个元素的游标值
return(E) elementData[lastRet = i];
}
//移除当前的元素(next()获得的元素,cursor已经指向下一个)
publicvoid remove(){
//上一个元素不存在
if(lastRet <0)
thrownewIllegalStateException();
checkForComodification();//检查是否修改
try{
ArrayList.this.remove(lastRet);//移除lastRet处的元素
cursor = lastRet;
lastRet =-1;
expectedModCount = modCount;
}catch(IndexOutOfBoundsException ex){
thrownewConcurrentModificationException();
}
}
/**
* 对剩余未迭代的元素进行指定操作,直到所有的元素都已经被处理或行动将抛出一个异常
*/
@Override
@SuppressWarnings("unchecked")
publicvoid forEachRemaining(Consumer<?super E> consumer){
Objects.requireNonNull(consumer);
finalint size =ArrayList.this.size;
int i = cursor;
//已经遍历完成,不需要继续遍历
if(i >= size){
return;
}
finalObject[] elementData =ArrayList.this.elementData;
if(i >= elementData.length){
thrownewConcurrentModificationException();
}
while(i != size && modCount == expectedModCount){
consumer.accept((E) elementData[i++]);
}
// 更新游标和上一次返回的元素,并检测是否修改了列表结构
cursor = i;
lastRet = i -1;
checkForComodification();
}
finalvoid checkForComodification(){
if(modCount != expectedModCount)
thrownewConcurrentModificationException();
}
}
/**
* AbstractList.ListItr的优化,继承自Iter
*/
privateclassListItrextendsItrimplementsListIterator<E>{
ListItr(int index){
super();
cursor = index;//指定第一个需要返回的元素为index
}
//返回是否有前一个元素,直到到列表的第0个元素
publicboolean hasPrevious(){
return cursor !=0;
}
//返回下一个元素的游标
publicint nextIndex(){
return cursor;
}
//返回上一个元素的游标
publicint previousIndex(){
return cursor -1;
}
//获取上一个元素
@SuppressWarnings("unchecked")
public E previous(){
checkForComodification();//检查是否修改了列表的结构
int i = cursor -1;//获得上一个元素索引
//数组越界则抛出异常
if(i <0)
thrownewNoSuchElementException();
Object[] elementData =ArrayList.this.elementData;
if(i >= elementData.length)
thrownewConcurrentModificationException();
cursor = i;//修改游标,下一个元素还是当前返回的previous元素
return(E) elementData[lastRet = i];
}
//设置当前元素(lastRet指向的值)的值为e
publicvoidset(E e){
if(lastRet <0)
thrownewIllegalStateException();
checkForComodification();
try{
ArrayList.this.set(lastRet, e);
}catch(IndexOutOfBoundsException ex){
thrownewConcurrentModificationException();
}
}
//在下一个游标处添加一个元素(remove的时候,游标回到移除的元素位置)
publicvoid add(E e){
checkForComodification();
try{
int i = cursor;
ArrayList.this.add(i, e);
cursor = i +1;
lastRet =-1;
expectedModCount = modCount;
}catch(IndexOutOfBoundsException ex){
thrownewConcurrentModificationException();
}
}
}
/**
* 返回一个子列表,子列表的范围为列表[fromIndex,toIndex)之间的元素,不包括同Index
* 如果fromIndex和同Index相同,则返回空列表
* 不创建新的List,在SubList中持有一个当前ArrayList实例的引用,以及子列表的索引范围
* 子列表的语义将变得不明确如果当前ArrayList实例结构发生变化(增删、扩容)
* @throws IndexOutOfBoundsException {@inheritDoc}
* @throws IllegalArgumentException {@inheritDoc}
*/
publicList<E> subList(int fromIndex,int toIndex){
subListRangeCheck(fromIndex, toIndex, size);
returnnewSubList(this,0, fromIndex, toIndex);
}
//检查子列表范围是否正确
staticvoid subListRangeCheck(int fromIndex,int toIndex,int size){
if(fromIndex <0)
thrownewIndexOutOfBoundsException("fromIndex = "+ fromIndex);
if(toIndex > size)
thrownewIndexOutOfBoundsException("toIndex = "+ toIndex);
if(fromIndex > toIndex)
thrownewIllegalArgumentException("fromIndex("+ fromIndex +
") > toIndex("+ toIndex +")");
}
/*Sublist-Start*/
//定义子列表类,维持一个获得子列表的ArrayList实例以及偏移量
//子列表偏移量和列表大小
privateclassSubListextendsAbstractList<E>implementsRandomAccess{
privatefinalAbstractList<E> parent;
privatefinalint parentOffset;
privatefinalint 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;
}
//设置index处的值为e,直接操作父列表,需要检查范围
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;
}
//获取index处的值,需要检查范围,并检查是否有修改
public E get(int index){
rangeCheck(index);
checkForComodification();
returnArrayList.this.elementData(offset + index);
}
//获得子列表的大小,检查是否有修改
publicint size(){
checkForComodification();
returnthis.size;
}
//在index处添加一个元素e,需要检查范围和是否有修改
publicvoid add(int index, E e){
rangeCheckForAdd(index);
checkForComodification();
parent.add(parentOffset + index, e);
this.modCount = parent.modCount;
this.size++;
}
//移除index处的元素,并返回删除的元素
public E remove(int index){
rangeCheck(index);
checkForComodification();
E result = parent.remove(parentOffset + index);
this.modCount = parent.modCount;
this.size--;
return result;
}
//移除[fromIndex,toIndex)之间的元素,检查是否有修改列表结构
protectedvoid removeRange(int fromIndex,int toIndex){
checkForComodification();
parent.removeRange(parentOffset + fromIndex,
parentOffset + toIndex);
this.modCount = parent.modCount;
this.size -= toIndex - fromIndex;
}
//在子列表末尾添加c中所有元素
publicboolean addAll(Collection<?extends E> c){
return addAll(this.size, c);
}
//在子列表index起添加c中所有元素,需要检查范围和是否有修改
publicboolean addAll(int index,Collection<?extends E> c){
rangeCheckForAdd(index);
int cSize = c.size();
if(cSize==0)
returnfalse;
checkForComodification();
parent.addAll(parentOffset + index, c);
this.modCount = parent.modCount;
this.size += cSize;
returntrue;
}
//获得迭代器
publicIterator<E> iterator(){
return listIterator();
}
//获得ListIterator迭代器(可向前、向后)
publicListIterator<E> listIterator(finalint index){
checkForComodification();
rangeCheckForAdd(index);
finalint offset =this.offset;
returnnewListIterator<E>(){
int cursor = index;
int lastRet =-1;
int expectedModCount =ArrayList.this.modCount;
publicboolean hasNext(){
return cursor !=SubList.this.size;
}
@SuppressWarnings("unchecked")
public E next(){
checkForComodification();
int i = cursor;
if(i >=SubList.this.size)
thrownewNoSuchElementException();
Object[] elementData =ArrayList.this.elementData;
if(offset + i >= elementData.length)
thrownewConcurrentModificationException();
cursor = i +1;
return(E) elementData[offset +(lastRet = i)];
}
publicboolean hasPrevious(){
return cursor !=0;
}
@SuppressWarnings("unchecked")
public E previous(){
checkForComodification();
int i = cursor -1;
if(i <0)
thrownewNoSuchElementException();
Object[] elementData =ArrayList.this.elementData;
if(offset + i >= elementData.length)
thrownewConcurrentModificationException();
cursor = i;
return(E) elementData[offset +(lastRet = i)];
}
//对未迭代的元素进行特定的操作,并将游标移到迭代完成的位置
@SuppressWarnings("unchecked")
publicvoid forEachRemaining(Consumer<?super E> consumer){
Objects.requireNonNull(consumer);
finalint size =SubList.this.size;
int i = cursor;
if(i >= size){
return;
}
finalObject[] elementData =ArrayList.this.elementData;
if(offset + i >= elementData.length){
thrownewConcurrentModificationException();
}
while(i != size && modCount == expectedModCount){
consumer.accept((E) elementData[offset +(i++)]);
}
//更新游标
lastRet = cursor = i;
checkForComodification();
}
publicint nextIndex(){
return cursor;
}
publicint previousIndex(){
return cursor -1;
}
publicvoid remove(){
if(lastRet <0)
thrownewIllegalStateException();
checkForComodification();
try{
SubList.this.remove(lastRet);
cursor = lastRet;
lastRet =-1;
expectedModCount =ArrayList.this.modCount;
}catch(IndexOutOfBoundsException ex){
thrownewConcurrentModificationException();
}
}
publicvoidset(E e){
if(lastRet <0)
thrownewIllegalStateException();
checkForComodification();
try{
ArrayList.this.set(offset + lastRet, e);
}catch(IndexOutOfBoundsException ex){
thrownewConcurrentModificationException();
}
}
publicvoid 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){
thrownewConcurrentModificationException();
}
}
finalvoid checkForComodification(){
if(expectedModCount !=ArrayList.this.modCount)
thrownewConcurrentModificationException();
}
};
}
//从当前子序列获得子序列,offset当前子列表位于最原始的列表的偏移
publicList<E> subList(int fromIndex,int toIndex){
subListRangeCheck(fromIndex, toIndex, size);
returnnewSubList(this, offset, fromIndex, toIndex);
}
//检查当前索引的范围是否正确
privatevoid rangeCheck(int index){
if(index <0|| index >=this.size)
thrownewIndexOutOfBoundsException(outOfBoundsMsg(index));
}
//检查当前索引的范围是否正确
privatevoid rangeCheckForAdd(int index){
if(index <0|| index >this.size)
thrownewIndexOutOfBoundsException(outOfBoundsMsg(index));
}
//生成索引越界错误消息
privateString outOfBoundsMsg(int index){
return"Index: "+index+", Size: "+this.size;
}
//判断是否有修改
privatevoid checkForComodification(){
if(ArrayList.this.modCount !=this.modCount)
thrownewConcurrentModificationException();
}
publicSpliterator<E> spliterator(){
checkForComodification();
//子列表的已经不是第一次使用
//fence 为父列表中属于子列表的最后一个元素的索引
returnnewArrayListSpliterator<E>(ArrayList.this, offset,
offset +this.size,this.modCount);
}
}
/**
* 对数组中的元素执行特定的操作,不允许在此过程中修改
*/
@Override
publicvoid forEach(Consumer<?super E> action){
Objects.requireNonNull(action);
finalint expectedModCount = modCount;
@SuppressWarnings("unchecked")
final E[] elementData =(E[])this.elementData;
finalint size =this.size;
for(int i=0; modCount == expectedModCount && i < size; i++){
action.accept(elementData[i]);
}
if(modCount != expectedModCount){
thrownewConcurrentModificationException();
}
}
/**
* 在列表上创建一个延迟绑定和fail-fast机制
*
* Spliterator提供列表的遍历和元素分割
*
* @return a {@code Spliterator} over the elements in this list
* @since 1.8
*/
@Override
publicSpliterator<E> spliterator(){
returnnewArrayListSpliterator<>(this,0,-1,0);
}
/** Index-based split-by-two, lazily initialized Spliterator */
staticfinalclassArrayListSpliterator<E>implementsSpliterator<E>{
/*
* 实在看不懂 ==!
* 如果ArrayList是不可变或者结构上不可变的(adds,removs等),可以使用
* Arrays.spliterator来实现。遍历过程中,不牺牲太多性能的情况下,我们可以检测到
* 干扰。(不太通,Instead we detect as much interference during traversal
* as practical without sacrificing much performance.) 我们主要依赖于
* modCounts。虽然这并不能保证检查到并发访问冲突,而且有时对于线程间的干扰过于保
* 守,但是发现足够的问题在实践中是值得的。为了实现这个功能,做了以下几点:
* 1. 延迟初始化fence和expectedModCount直到需要我们提交我们正在检测的状态信息
* 以此提高精确性(这不适用于子列表,子列表使用非延迟加载值)
* 2. 只在forEach结束时检测一次ConcurrentModificationException异常(性能最
* 敏感的方法)。使用forEach(与迭代器相反),我们通常只能在action操作之后检测
* 干扰,而不是开始之前。因为干扰的原因,假设如null或者列表元素很小,更进一步的
* CME-triggering检测将应用于所有的可能破外。这允许forEach内部的循环在运行时不
* 进行进一步检查,简化lambda表达式的操作。虽然这确实需要大量的检查(
* list.stream().forEach(a)相同的情况), 没有其他的检测和计算发生在forEach内,
* 其他不常使用的方法不能从流中获得大部分性能
*/
privatefinalArrayList<E> list;
privateint index;// 当前的索引(advance/split操作的对象)
privateint fence;// -1 until used; then one past last index
privateint expectedModCount;// 当fence设置后初始化
/** 根据范围创建一个Spliterator */
ArrayListSpliterator(ArrayList<E> list,int origin,int fence,
int expectedModCount){
this.list = list;// 可以是null(除非需要遍历)
this.index = origin;
this.fence = fence;
this.expectedModCount = expectedModCount;
}
privateint getFence(){// 第一次使用时,初始化fence为size
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;//初始化expectedModCount
hi = fence = lst.size;
}
}
return hi;
}
publicArrayListSpliterator<E> trySplit(){
//求中间索引,>>>无符号右移,高位补0
int hi = getFence(), lo = index, mid =(lo + hi)>>>1;
return(lo >= mid)?null:// 分成两份,如果列表太小返回null
newArrayListSpliterator<E>(list, lo, index = mid,
expectedModCount);
}
//执行特定操作,用于遍历,每调用一次,index增大,知道fence(也即到列表末尾)
publicboolean tryAdvance(Consumer<?super E> action){
if(action ==null)
thrownewNullPointerException();
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)
thrownewConcurrentModificationException();
returntrue;
}
returnfalse;
}
//遍历执行特定操作
publicvoid forEachRemaining(Consumer<?super E> action){
int i, hi, mc;// hoist accesses and checks from loop
ArrayList<E> lst;Object[] a;
if(action ==null)
thrownewNullPointerException();
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;
}
}
thrownewConcurrentModificationException();
}
//获得还剩余的未遍历的元素数
publiclong estimateSize(){
return(long)(getFence()- index);
}
//Spliterator特征
publicint characteristics(){
returnSpliterator.ORDERED |Spliterator.SIZED |Spliterator.SUBSIZED;
}
}
/**
* 根据条件移除元素,元素有移除,则返回true
*/
@Override
publicboolean 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;
finalBitSet removeSet =newBitSet(size);
finalint expectedModCount = modCount;
finalint 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);//设置第i位为1,标记移除
removeCount++;//记录移除的记录数
}
}
//此过程中发生列表结构修改,抛出异常
if(modCount != expectedModCount){
thrownewConcurrentModificationException();
}
// 将没有移除的元素向前移动
finalboolean anyToRemove = removeCount >0;
if(anyToRemove){
finalint newSize = size - removeCount;
for(int i=0, j=0;(i < size)&&(j < newSize); i++, j++){
//找到i之后第一个为false的index,也即未标记移除的
i = removeSet.nextClearBit(i);
elementData[j]= elementData[i];
}
for(int k=newSize; k < size; k++){
elementData[k]=null;//清除需要删除的引用,以让垃圾回收器回收
}
this.size = newSize;//更新尺寸
//此过程中发生列表结构修改,抛出异常
if(modCount != expectedModCount){
thrownewConcurrentModificationException();
}
modCount++;
}
//移除元素,则返回true
return anyToRemove;
}
/**
* 对列表中每一个元素根据传入的UnaryOperator,执行特定操作,并用返回值替换原来的值
*/
@Override
@SuppressWarnings("unchecked")
publicvoid replaceAll(UnaryOperator<E>operator){
Objects.requireNonNull(operator);
finalint expectedModCount = modCount;
finalint size =this.size;
for(int i=0; modCount == expectedModCount && i < size; i++){
//执行特定操作,并用返回值替换原来的值
elementData[i]=operator.apply((E) elementData[i]);
}
if(modCount != expectedModCount){
thrownewConcurrentModificationException();
}
modCount++;
}
//根据传入的比较器c对列表进行排序
@Override
@SuppressWarnings("unchecked")
publicvoid sort(Comparator<?super E> c){
finalint expectedModCount = modCount;
Arrays.sort((E[]) elementData,0, size, c);
//排序过程中发生列表结构变化,则抛出异常
if(modCount != expectedModCount){
thrownewConcurrentModificationException();
}
modCount++;
}
}
ArrayList 中的很大部分操作,使用了Arrays.copyof()和System.arraycopy()进行数组的拷贝,需要进一步分析其源码
列表的排序使用Arrays.sort(),进一步分析其源码
标签:
原文地址:http://www.cnblogs.com/ggmfengyangdi/p/5738491.html