0

I m trying to loop a group of people and for every person i get the friends. Then loop through the friends and for every friend get his friends and call a method called groupPeople(). But there i m getting ConcurrentModificationException. Any idea why ?

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++;
            }
        }
    }

The exception message :

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)
9
  • 1
    What is exactly the stacktrace and Which line dors it concern? Sep 22, 2015 at 20:20
  • in the line User setElement = iterator.next(); Sep 22, 2015 at 20:22
  • 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) Sep 22, 2015 at 20:24
  • Post your groupPeople() method. Sep 22, 2015 at 20:27
  • 2
    It looks like when you do user.addFriend() in groupPeople(), the original listofFriends is getting altered. The iterator was obtained from listofFriends in the beginning and listofFriends is altered afterwards, which may be causing ConcurrentModificationException. Sep 22, 2015 at 20:37

1 Answer 1

1

Most likely you are altering the Set<User> listofFriends in one of these methods e.g. groupPeople

This could be because a User is friend of themselves, or listOfFriends2 is the same Set, or something else you are doing in the method you call.

I suggest you step through the code in your debugger to find the problem.

1
  • @AkinDönmez You don't show where in your code you are getting the error which is much more interesting. The basic problem is you can't be modifying a HashMap or HashSet while you are iterating over it. Either you need to take a copy of the things you want to change, take a copy of the keys, or use a collection which supports concurrent access such as a ConcurrentHashMap Sep 23, 2015 at 12:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.