Akin Dönmez
Akin Dönmez

Reputation: 363

ConcurrentModificationException and no idea why?

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)

Upvotes: 0

Views: 417

Answers (1)

Peter Lawrey
Peter Lawrey

Reputation: 533462

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.

Upvotes: 1

Related Questions