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 workreturn oldValue;}
4. 跟新
按照索引来更新值
public E set(int index, E element){rangeCheck(index);
E oldValue =elementData(index);
elementData[index]= element;return oldValue;}
5. 遍历,容器中使用了迭代器模式,使用Iterator可以进行遍历
内置迭代器
public Iterator<E>iterator(){returnnewItr();}/**
* An optimized version of AbstractList.Itr
*/privateclassItrimplementsIterator<E>{//表示下一个元素的索引int cursor;// index of next element to return//表示上次返回的索引值,如果是-1表示,上次操作是删除,或者是刚开始操作int lastRet =-1;// index of last element returned; -1 if no such//记录一开始的修改记录,用于在遍历的过程中,如果外部调用了非迭代器的修改Array元素的方法,就会执行报错机制int expectedModCount = modCount;Itr(){}publicbooleanhasNext(){return cursor != size;}@SuppressWarnings("unchecked")public E next(){//验证报错机制checkForComodification();int i = cursor;if(i >= size)thrownewNoSuchElementException();
Object[] elementData = ArrayList.this.elementData;if(i >= elementData.length)thrownewConcurrentModificationException();
cursor = i +1;return(E) elementData[lastRet = i];}publicvoidremove(){if(lastRet <0)thrownewIllegalStateException();checkForComodification();try{
ArrayList.this.remove(lastRet);
cursor = lastRet;
lastRet =-1;//使用迭代器可以在遍历的同时,删除元素
expectedModCount = modCount;}catch(IndexOutOfBoundsException ex){thrownewConcurrentModificationException();}}//校验是否被更改过finalvoidcheckForComodification(){if(modCount != expectedModCount)thrownewConcurrentModificationException();}}