我是靠谱客的博主 专一鼠标,这篇文章主要介绍异常:java.util.ConcurrentModificationException,现在分享给大家,希望可以做个参考。

复制代码
1
重现异常:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
复制代码
import java.util.ArrayList;
import java.util.Iterator;

class User {
    private String userName, password;
    private int ID;

    User(int p_ID, String p_userName, String p_password) {
        ID = p_ID;
        userName = p_userName;
        password = p_password;
    }
}

public class Test {
    static ArrayList al = new ArrayList();

    public static void main(String[] args) {
        add();
        clear();
    }

    public static void add() {
        for (int i = 0; i < 5; i++) {
            al.add(new User(i, "userName", "password"));
        }
    }

    public static void clear() {
        Iterator it = ((ArrayList) al).iterator();
        while (it.hasNext()) {
            User usr = (User) (it.next());
            int index = al.indexOf(usr);
            al.remove(index);
            // it.remove();
        }
        System.out.println("Cleard");
    }
}

注意到上面代码中注释部分的上面2句,那就是异常出现的根源,我从ArrayList的一个对象al中移去了项目,然而Iterator对象it并不知道al中已经发生了变化,所以再继续遍历的时候会发生错误。正确的写法应该如注释行所示,然后注释行去掉上面的2行。


在Map或者Collection的时候,不要用它们的API直接修改集合的内容,如果要修改可以用Iterator的remove()方法,例如:

    public void setReparation( Reparation reparation ) {
        for (Iterator it = this.reparations.iterator();it.hasNext();){    //reparations为Collection
            Reparation repa = (Reparation)it.next();
            if (repa.getId() == reparation.getId()){
                this.reparations.remove(repa);
                this.reparations.add(reparation);
            }
        }
   }

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

    public void setReparation( Reparation reparation ) {
        boolean flag = false;
        for (Iterator it = this.reparations.iterator();it.hasNext();){    //reparations为Collection
            Reparation repa = (Reparation)it.next();
            if (repa.getId() == reparation.getId()){
                it.remove();
                flag = true;
                break;
            }
        }
        if(flag){
          this.reparations.add(reparation);
        }
    }

最后

以上就是专一鼠标最近收集整理的关于异常:java.util.ConcurrentModificationException的全部内容,更多相关异常:java内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(56)

评论列表共有 0 条评论

立即
投稿
返回
顶部