在使用iterator的时候为什么要先next再remove不然就会抛错呢
@org.junit.Test
public void testArrayList(){ArrayList <Integer>list =new ArrayList<Integer>();
list.add(1);
list.add(2);
list.add(3);
Iterator<?> it=list.iterator();
System.out.println(list);
while(it.hasNext()){
it.next();
it.remove();
System.out.println(list);
}
}
看一下jdk的实现
private class Itr implements Iterator<E> {
int cursor; // index of next element to return 这个是next之后的位置坐标,初始值是0,JVM的初始化
int lastRet = -1; // index of last element returned; -1 if no such 这个是next之前的位置坐标
int expectedModCount = modCount; //这个是list集合的大小
public boolean hasNext() {
return cursor != size;//next以前的位置,从0开始
}
@SuppressWarnings("unchecked")
public E next() {
checkForComodification();
int i = cursor;
if (i >= size)
throw new NoSuchElementException();
Object[] elementData = ArrayList.this.elementData;//获得list内部的元素
if (i >= elementData.length)
throw new ConcurrentModificationException();
cursor = i + 1;//将位置推进1
return (E) elementData[lastRet = i];//记录下当前的位置 比如是0的时候 lastRet =0 lastRet =1
}
public void remove() {
if (lastRet < 0)
throw new IllegalStateException();
checkForComodification();
try {
ArrayList.this.remove(lastRet); //删除前一个元素
cursor = lastRet; //将指针回退
lastRet = -1;
expectedModCount = modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}
可以看得出来如果直接调用remove lastRet =-1 所以直接抛错 throw new IllegalStateException();.这么做的好处其实可以控制遍历时候数组越界提升性能,其中匠心得要细细的品味