ConcurrentModificationException
一个不该犯的低级错误,今天的代码突然抛了一个concurrentModificationException错误,
Iterator的一个基本概念没有掌握导致的这个错误,就是在Iterator的实现类
比如Hashtable里面的内部类
private class Enumerator
会在next,或者remove的时候检查当前集合是否会在修改状态,如果是的话
就会抛出 ConcurrentModificationException,而他自己remove则是使用了同步的方法
而且同步了modCount;expectedModCount;
public T next() { if (modCount != expectedModCount) throw new ConcurrentModificationException(); return nextElement(); } public void remove() { if (!iterator) throw new UnsupportedOperationException(); if (lastReturned == null) throw new IllegalStateException("Hashtable Enumerator"); if (modCount != expectedModCount) throw new ConcurrentModificationException(); synchronized(Hashtable.this) { Entry[] tab = Hashtable.this.table; int index = (lastReturned.hash & 0x7FFFFFFF) % tab.length; for (Entrye = tab[index], prev = null; e != null; prev = e, e = e.next) { if (e == lastReturned) { modCount++; expectedModCount++; if (prev == null) tab[index] = e.next; else prev.next = e.next; count--; lastReturned = null; return; } } throw new ConcurrentModificationException(); } } }
而自己在next的同时,修改了这个集合,导致了这个错误的出现