-2

The code given below dont throw a ConcurrentModificationException.But if i add 2 more elements into the LinkedList, it throws the Exception. Why ?

List<String> list = new LinkedList<String>();
list.add("A");
list.add("B");

for (String s : list) {
    if (s.equals("B")) {
        list.remove(s);
    }
}
Bibhudutta
  • 31
  • 3
  • See http://stackoverflow.com/a/223929/4290096 – Arun Xavier Jun 29 '15 at 13:25
  • possible duplicate of [Iterating through a list, avoiding ConcurrentModificationException when removing in loop](http://stackoverflow.com/questions/223918/iterating-through-a-list-avoiding-concurrentmodificationexception-when-removing) – nogard Jun 29 '15 at 13:26
  • I guess which question was asked more times, this or strings comparison.. – drgPP Jun 29 '15 at 13:27

2 Answers2

2

You can't remove items from a Collection while iterating over it using an enhanced for loop. What you want to do instead is this:

Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
  String s = iterator.next();
  if (s.equals("B")) {
    iterator.remove();
  }
}
Sam Estep
  • 12,974
  • 2
  • 37
  • 75
  • I know Iterator is good for such operations, but i m curious to know why only the last and 2nd last elements are removed from the linkedList without throwing the ConcurrentModificationException ? – Bibhudutta Jun 29 '15 at 13:38
1

You cant remove an entry from a list in a for loop, you have to use an iterator, like that:

List<String> list = new LinkedList<String>();
list.add("A");
list.add("B");
Iterator<String> iterator = list.iterator();
while(iterator.hasNext()) {
  String entry = iterator.next();
  if(entry.equals("B") {
   iterator.remove();
  }
}
Arthur Eirich
  • 3,368
  • 9
  • 31
  • 63