public Object clone(){try{//先调用父类的clone克隆
ArrayList<?> v =(ArrayList<?>)super.clone();//底层还是调用System.arraycopy();
v.elementData = Arrays.copyOf(elementData, size);//修改次数设置为0
v.modCount =0;return v;}catch(CloneNotSupportedException e){// this shouldn't happen, since we are CloneablethrownewInternalError(e);}}
get方法
public E get(int index){//首先检查index是否合法rangeCheck(index);returnelementData(index);}/**
*检查index是否合法
*/privatevoidrangeCheck(int index){if(index >= size)thrownewIndexOutOfBoundsException(outOfBoundsMsg(index));}/**
*返回index 位置的元素
*/
E elementData(int index){return(E) elementData[index];}
set方法
public E set(int index, E element){//检查index是否合法rangeCheck(index);//取出旧元素
E oldValue =elementData(index);//把index位置的元素替换为新元素
elementData[index]= element;return oldValue;}
privatevoidgrow(int minCapacity){// 记录旧容量int oldCapacity = elementData.length;//新容量为 旧容量+ 旧容量的1/2//这里使用了移位运算 右移一位相当于除以2int newCapacity = oldCapacity +(oldCapacity >>1);//取一个最大值if(newCapacity - minCapacity <0)
newCapacity = minCapacity;//如果新容量超过Integer.MAX_VALUE - 8 则把newCapacity赋值为Integer.MAX_VALUEif(newCapacity - MAX_ARRAY_SIZE >0)
newCapacity =hugeCapacity(minCapacity);// minCapacity is usually close to size, so this is a win:
elementData = Arrays.copyOf(elementData, newCapacity);}privatestaticinthugeCapacity(int minCapacity){if(minCapacity <0)// overflowthrownewOutOfMemoryError();return(minCapacity > MAX_ARRAY_SIZE)?
Integer.MAX_VALUE :
MAX_ARRAY_SIZE;}
remove方法
public E remove(int index){//检查下标是否合法rangeCheck(index);//修改次数+1
modCount++;//保存旧值
E oldValue =elementData(index);//删除元素后 数组需要移动的元素数量int numMoved = size - index -1;if(numMoved >0)//移动数组
System.arraycopy(elementData, index +1, elementData, index,
numMoved);//置为null 方便gc
elementData[--size]= null;// clear to let GC do its workreturn oldValue;}
clear方法
publicvoidclear(){//修改次数+1
modCount++;// clear to let GC do its workfor(int i =0; i < size; i++)
elementData[i]= null;
size =0;}