https://www.cnblogs.com/chrischennx/p/9610853.htmlhtml
正確方式java
方法一,仍是fori,位置前挪了減回去就好了, remove後i--:this
public void testListForiRight() { List<String> list = new ArrayList<>(); list.add("1"); list.add("2"); list.add("3"); for (int i = 0; i < list.size(); i++) { System.out.println(list.get(i)); list.remove(i); i--; //位置前挪了減回去就好了 } }
方法二,不用ArrayList的remove方法,用Itr本身定義的remove方法,代碼以下:spa
@Test public void testIteratorRemove() { List<String> list = new ArrayList<>(); list.add("1"); list.add("2"); list.add("3"); Iterator<String> itr = list.iterator(); while (itr.hasNext()) { String s = itr.next(); System.out.println(s); itr.remove(); } }
爲何itr本身定義的remove就不報錯了呢?看下源碼:code
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(); } }
依然有 checkForComodification()
校驗,可是看到後面又從新賦值了,因此又相等了。htm