java - ConcurrentModificationException 不知道为什么?

标签 java set concurrentmodification

我正在尝试循环一群人,并且为每个人找到 friend 。然后循环遍历 friend ,并为每个 friend 获取他的 friend 并调用名为 groupPeople() 的方法。但我得到了 ConcurrentModificationException。知道为什么吗?

for (User user : this.groupA) {
            Set<User> listofFriends = user.getFriends();
             Iterator<User> iterator = listofFriends.iterator();
                while(iterator.hasNext()) {
                    User setElement = iterator.next();
                    Set<User> listofFriends2 = setElement.getFriends();
                    groupPeople(listofFriends2,10);
                }
        }
private void groupPeople(Set<User> group,int number) {
        for (User user : group) {
            int y = 0;
            while(y<number){
                user.addFriend(socialNetwork.getPeopleInNetwork().get(++counter));
                y++;
            }
        }
    }

异常消息:

Exception in thread "main" java.util.ConcurrentModificationException
  at java.util.HashMap$HashIterator.nextEntry(HashMap.java:922)
  at java.util.HashMap$KeyIterator.next(HashMap.java:956)

最佳答案

您很可能正在更改 Set<User> listofFriends在这些方法之一中,例如groupPeople

这可能是因为用户是他们自己的 friend ,或者 listOfFriends2是同一个 Set,或者是您在调用的方法中执行的其他操作。

我建议您在调试器中单步执行代码来查找问题。

关于java - ConcurrentModificationException 不知道为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32726074/

相关文章:

java - 删除组内重复的列值

java - 序列化 HttpSession 对象

java - 在一对多关系的列上创建索引

algorithm - 带移位算法的最小位串集合并集

C++ STL 集 : Compare object with extrinsic state

java - 浏览器不缓存资源( header 设置)

python - 找到最小的解决方案集,如果存在(两个乘数)

java - 并发修改异常问题

android - 为什么在运行我的应用程序一段时间后出现 ConcurrentModificationException?

java - 使用枚举类型创建的单例,线程安全问题