我正在尝试循环一群人,并且为每个人找到 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/