//调用ArrayList的该方法返回内部实现Iterator接口的Itr对象 public Iterator<E> iterator(){ returnnew Itr(); }
privateclassItrimplementsIterator<E> { //下一个元素的下标 int cursor; // index of next element to return int lastRet = -1; // index of last element returned; -1 if no such int expectedModCount = modCount;
@SuppressWarnings("unchecked") public E next(){ //检查被迭代的对象是否被修改过 checkForComodification(); int i = cursor; //如果下标大于等于容器中元素的实际大小抛出异常 if (i >= size) thrownew NoSuchElementException(); Object[] elementData = ArrayList.this.elementData; //如果下标大于等于列表长度,抛出异常 if (i >= elementData.length) thrownew ConcurrentModificationException(); //更新下个元素的下标 cursor = i + 1; //返回列表中当前下标的元素,并对lastRet赋值 return (E) elementData[lastRet = i]; }
publicvoidremove(){ //如果lastRet小于0代表没调用过next()方法,抛出异常 if (lastRet < 0) thrownew IllegalStateException(); //检查被迭代的对象是否被修改过 checkForComodification();
@Test publicvoidtest2(){ List list = new ArrayList(); list.add(1); list.add(2); list.add(3); Iterator iterator = list.iterator(); //while遍历 while (iterator.hasNext()) { System.out.println(iterator.next());
} }
运行结果
1 2 3
1 2 3
如果如上面所说在循环过程中修改list的列表对象,看是否会引发异常。我们队上面代码简单修改一下。
1 2 3 4 5 6 7 8 9 10 11 12 13
@Test publicvoidtest2(){ List list = new ArrayList(); list.add(1); list.add(2); list.add(3);
java.util.ConcurrentModificationException at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:909) at java.util.ArrayList$Itr.next(ArrayList.java:859) at com.lwx.arraylist.ArrayListTest.test2(ArrayListTest.java:40)