为什么会出现 java.util.ConcurrentModificationException 异常?
在Map或者Collection的时候,不要用它们的API直接修改集合的内容(否则会出现 java.util.ConcurrentModificationException 异常),如果要修改可以用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 }
10
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 }
10
如上写会在运行期报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 }
15
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 }
15