现在的位置: 首页 > 综合 > 正文

ConcurrentModificationException

2013年10月19日 ⁄ 综合 ⁄ 共 2516字 ⁄ 字号 评论关闭

突然抛了一个concurrentModificationException错误,Iterator的一个基本概念没有掌握导致的这个错误,就是在Iterator的实现类。比如Hashtable里面的内部类

 private class Enumerator<T> implements Enumeration<T>, Iterator<T>

会在next,或者remove的时候检查当前集合是否会在修改状态,如果是的话,就会抛出 ConcurrentModificationException,而他自己remove则是使用了同步的方法,而且同步了modCount;expectedModCount;

复制代码
 1 public T next() {
 2      if (modCount != expectedModCount)
 3          throw new ConcurrentModificationException();
 4      return nextElement();
 5  }
 6 
 7 
 8 public void remove() {
 9      if (!iterator)
10         throw new UnsupportedOperationException();
11      if (lastReturned == null)
12         throw new IllegalStateException("Hashtable Enumerator");
13      if (modCount != expectedModCount)
14         throw new ConcurrentModificationException();
15 
16      synchronized(Hashtable.this) {
17         Entry[] tab = Hashtable.this.table;
18         int index = (lastReturned.hash & 0x7FFFFFFF) % tab.length;
19 
20      for (Entry<K,V> e = tab[index], prev = null; e != null;
prev = e, e = e.next) {
22       if (e == lastReturned) {
23          modCount++;
24          expectedModCount++;
25          if (prev == null)
26             tab[index] = e.next;
27          else
28             prev.next = e.next;
29          count--;
30          lastReturned = null;
31          return;
32       }
33      }
34      throw new ConcurrentModificationException();
35      }
36    
}
37     }
复制代码
而自己在next的同时,修改了这个集合,导致了这个错误的出现

 

在Map或者Collection的时候,不要用它们的API直接修改集合的内容,如果要修改可以用Iterator的remove()方法,例如:
复制代码
1 public void setReparation( Reparation reparation ) {
2         for (Iterator it = this.reparations.iterator();it.hasNext();){    //reparations为Collection
3             Reparation repa = (Reparation)it.next();
4             if (repa.getId() == reparation.getId()){
5                 this.reparations.remove(repa);
6                 this.reparations.add(reparation);
7             }
8         }
9    }
复制代码

 

如上写会在运行期报ConcurrentModificationException,可以如下修改:

 

复制代码
 1  public void setReparation( Reparation reparation ) {
 2         boolean flag = false;
 3         for (Iterator it = this.reparations.iterator();it.hasNext();){    //reparations为Collection
 4             Reparation repa = (Reparation)it.next();
 5             if (repa.getId() == reparation.getId()){
 6                 it.remove();
 7                 flag = true;
 8                 break;
 9             }
10         }
11         if(flag){
12           this.reparations.add(reparation);
13         }
14     }
复制代码

 

 

原文摘自
alreal
 

http://www.blogjava.net/EvanLiu/archive/2008/08/31/224453.html

http://blog.sina.com.cn/s/blog_670eabd10100n7qa.html

抱歉!评论已关闭.