List<String> a = newArrayList<>(100); a.add("1"); a.add("2"); a.add("1"); for (String temp : a) { if ("1".equals(temp)) { a.remove(temp); System.out.println("1---"); } else { System.out.println("2---"); } }
代码3
1 2 3 4 5 6 7 8 9 10 11 12
List<String> a = newArrayList<>(100); a.add("1"); a.add("2"); a.add("1"); for (String temp : a) { if ("1".equals(temp)) { System.out.println("1---"); } else { a.remove(temp); System.out.println("2---"); } }
运行结果分别是:
代码2运行结果
1 2 3 4
1--- Exception in thread "main" java.util.ConcurrentModificationException at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:901) at java.util.ArrayList$Itr.next(ArrayList.java:851)
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; }
privateclassItrimplementsIterator<E> { int cursor; // index of next element to return intlastRet= -1; // index of last element returned; -1 if no such intexpectedModCount= modCount;
publicbooleanhasNext() { return cursor != size; }
@SuppressWarnings("unchecked") public E next() { 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]; }
publicvoidremove() { if (lastRet < 0) thrownewIllegalStateException(); checkForComodification();
@Override @SuppressWarnings("unchecked") publicvoidforEachRemaining(Consumer<? super E> consumer) { Objects.requireNonNull(consumer); finalintsize= ArrayList.this.size; inti= cursor; if (i >= size) { return; } final Object[] elementData = ArrayList.this.elementData; if (i >= elementData.length) { thrownewConcurrentModificationException(); } while (i != size && modCount == expectedModCount) { consumer.accept((E) elementData[i++]); } // update once at end of iteration to reduce heap write traffic cursor = i; lastRet = i - 1; checkForComodification(); }
finalvoidcheckForComodification() { if (modCount != expectedModCount) thrownewConcurrentModificationException(); } }