List<String> aa = new ArrayList<String>(); aa.add("F1"); aa.add("F2"); aa.add("F3"); for (String temp : aa) { if ("F3".equals(temp)) { aa.remove(temp); } } for (String temp : aa){ System.out.println(temp); }
———————————————— 版权声明:本文为CSDN博主「enable1234___」的原创文章,遵循CC 4.0 by-sa版权协议,转载请附上原文出处链接及本声明。 原文链接:https://blog.csdn.net/Enable1234___/article/details/53792440
for(I #i = expression.iterator; #i.hasNext(); ){ var x = #i.next(); }第一步:进入hasNext()方法。
public boolean hasNext() { return cursor != size; } @SuppressWarnings("unchecked") public E next() { checkForComodification();//此处报错 int i = cursor; if (i >= size) throw new NoSuchElementException(); Object[] elementData = ArrayList.this.elementData; if (i >= elementData.length) throw new ConcurrentModificationException(); cursor = i + 1; return (E) elementData[lastRet = i]; } final void checkForComodification() { if (modCount != expectedModCount) throw new ConcurrentModificationException(); }
final void checkForComodification() { if (modCount != expectedModCount) throw new ConcurrentModificationException(); } }
public boolean remove(Object o) { if (o == null) { for (int index = 0; index < size; index++) if (elementData[index] == null) { fastRemove(index); return true; } } else { for (int index = 0; index < size; index++) if (o.equals(elementData[index])) { fastRemove(index); return true; } } return false; }看,并没有对expectedModCount进行任何修改,导致expectedModCount和modCount不一致,抛出异常。所以,遍历list删除元素一律用Iterator这样不会报错,看看Iterator的remove()方法的源码,是对expectedModCount重新做了赋值处理的,如下:
public void remove() { if (lastRet < 0) throw new IllegalStateException(); checkForComodification(); try { ArrayList.this.remove(lastRet); cursor = lastRet; lastRet = -1; expectedModCount = modCount;//处理expectedModCount } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); }