0

I have this code:

public static void main(String[] args) {
    User user = new User("user1","user1",1l);
    User user1 = new User("user2","user2",2l);
    User user2 = new User("user3","user3",3l);

    List<User> list = new ArrayList<User>();
    list.add(user);
    list.add(user1);
    list.add(user2);

    for(User user3 : list){
        System.out.println(user3.getName());
        if(user3.getName().equals("user1")){
            list.remove(user3);
        }
    }
}

when executing this code , I get the following error:

Exception in thread "main" java.util.ConcurrentModificationException
    at java.util.AbstractList$Itr.checkForComodification(Unknown Source)
    at java.util.AbstractList$Itr.next(Unknown Source)

How can I avoid it?

Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
senior
  • 2,196
  • 6
  • 36
  • 54

2 Answers2

2

Use Iterator to iterate the list and then use Iterator.remove() to remove the particular element

Kick
  • 4,823
  • 3
  • 22
  • 29
1

When you are iterating through a list (collection) using the for-each loop, you should not try to modify the collection as it is undefined behaviour( even though internally it uses Iterator).

The best way to handle removal of elements while iterating through a collection is by using an Iterator.

Iterator<User> it = list.iterator();

while (it.hasNext()) {

  User user = it.next();
  if(user.getName().equals("user1")){
        it.remove();
   }

 }
Kakarot
  • 4,252
  • 2
  • 16
  • 18