//remove操作 //输入索引 public E remove(int index) { //检测这个元素是否处于数组的最后一个位置 rangeCheck(index); modCount++; EoldValue= elementData(index); intnumMoved= size - index - 1; if (numMoved > 0) //若index不在最后一位,则将index+1开始向后的所有元素向前移动一位,相当于删除了index位置的元素 System.arraycopy(elementData, index+1, elementData, index, numMoved); //将最后一位赋值为null elementData[--size] = null; // clear to let GC do its work return oldValue; } //参数直接为指定元素 publicbooleanremove(Object o) { if (o == null) { for (intindex=0; index < size; index++) if (elementData[index] == null) { fastRemove(index); returntrue; } } else { for (intindex=0; index < size; index++) if (o.equals(elementData[index])) { fastRemove(index); returntrue; } } returnfalse; }
privatevoidfastRemove(int index) { modCount++; intnumMoved= size - index - 1; if (numMoved > 0) System.arraycopy(elementData, index+1, elementData, index,numMoved); elementData[--size] = null; // clear to let GC do its work }
1 2 3 4 5 6
//get操作 public E get(int index) { rangeCheck(index); return elementData(index); } //由于arraylist的底层基于数组,获取元素就很简单,直接调用数组访问即可
//迭代器 //由上述源码可知,在进行remove的时候,size是时刻动态变化的,所以不能对arrayList进行for循环遍历来remove元素,这样容易造成结果不准确甚至数组下标越界 public Iterator<E> iterator() { returnnewItr(); } //当创建迭代器时 list.iterator();会直接返回一个Itr对象
//ArrayList的内部类Itr实现了Iterator接口,该类有三个方法 privateclassItrimplementsIterator<E> { intcursor=0 ; // index of next element to return,下一个要访问的元素 intlastRet= -1; // index of last element returned; -1 if no such intexpectedModCount= modCount;//代表对ArrayList修改次数的期望值,初始为modCount
publicbooleanhasNext() { return cursor != size; }
@SuppressWarnings("unchecked") public E next() { //判断expectedModCount是否和modCount相等 checkForComodification(); inti= cursor; //判断是否越界 if (i >= size) thrownewNoSuchElementException(); Object[] elementData = ArrayList.this.elementData; if (i >= elementData.length) thrownewConcurrentModificationException(); cursor = i + 1; return (E) elementData[lastRet = i];//lastRet和cursor都自增1,并返回自增后的lastRet }
publicvoidremove() { // if (lastRet < 0) thrownewIllegalStateException(); checkForComodification();