1

I m getting ConcurrentModificationException but i dont really understand why.. When i use an iterator shouldnt it supposed to work fine ?

public void nextDay(){
        int range = (10 - 0) + 1; 
        ListIterator<User> it = this.socialNetwork.getPeopleInNetwork().listIterator();    
        while(it.hasNext()) {

            User user = it.next();   
            int random = (int)(Math.random() * range) + 0;
            if(user.getFriends().size()<=25){
                try {

                    this.socialNetwork.getPeopleInNetwork().add(user.addFriend(new UserImpl("new","user")));
                    user.addFriend(this.socialNetwork.getPeopleInNetwork().get(random));
                } catch (IllegalArgumentException | UserAlreadyInFriendListException e) {
                    logger.error(e.getMessage());
                }
            }else{
                try {
                    this.socialNetwork.getPeopleInNetwork().add(user.addFriend(new UserImpl("new","user")));
                    this.socialNetwork.getPeopleInNetwork().add(user.addFriend(new UserImpl("new","user")));
                    this.socialNetwork.getPeopleInNetwork().add(user.addFriend(new UserImpl("new","user")));
                    user.addFriend(this.socialNetwork.getPeopleInNetwork().get(random));
                } catch (IllegalArgumentException | UserAlreadyInFriendListException e) {
                    logger.error(e.getMessage());
                }

            }
        }
    }
Akin Dönmez
  • 353
  • 8
  • 24
  • 1
    re `"...even though I'm using iterator..."` -- You've got this in the loop: `this.socialNetwork.getPeopleInNetwork().add(...)` an iterator does not protect you from concurrent modification when you modify the list **without** using the iterator. This should be common sense, no? – Hovercraft Full Of Eels Sep 09 '15 at 01:54

1 Answers1

3

No, you cannot modify the list while iterating it, unless you use the iterator itself to modify it.

You should create a copy and iterate the copy if you plan to modify the original list without using the iterator.

Otherwise, you can use the iterator to modify the list.

Take a look at the add method of ListIterator:

http://docs.oracle.com/javase/7/docs/api/java/util/ListIterator.html#add(E)

eugenioy
  • 11,825
  • 28
  • 35