-2

When I try to modify a collection while iterating through it, will result in ConcurrentModification exception (i.e., when using forEach and forEachRemaining)

But below code won't why?

List<String> list=new  ArrayList<>();  

list.add("ram");
list.add("ravi");
Iterator<String> it=list.iterator();
while(it.hasNext()){
  System.out.printing(it.next());
 it.remove();
}

1 Answers1

-1

You ask why

List<String> list = new ArrayList<>();  
Iterator<String> it = list.iterator();
while(it.hasNext()) {
    System.out.printing(it.next());
}

does not throw a CCME.

The answer is simple. A CCME is thrown if you modify a list while iterating it. You are iterating the list, but you are not modifying it at the same time. Therefore the condition for throwing a CCME is not satisfied.

(The same reasoning applies in the case of a non-empty list too ...)


Let me break it down for you. You said:

When I try to modify a collection while iterating through it, will result in ConcurrentModification exception.

(This is correct as a general statement, by the way. But not universally.)

Reducing that to simple propositional logic we get:

exception_thrown = iterating_collection AND modifying_collection

In your example

iterating_collection is TRUE

modifying_collection is FALSE

but

TRUE AND FALSE is FALSE

therefore

exception_thrown is FALSE

In English, CCME is not thrown.


Now for your updated code:

List<String> list = new ArrayList<>();  
list.add("ram");
list.add("ravi");
Iterator<String> it = list.iterator();
while (it.hasNext()) {
    System.out.printing(it.next());
    it.remove();
}

In this case, you are modifying the collection using the iterator. This is the one situation where you are allowed to modify a collection while iterating it.

Think about it. If Iterator.remove() was not permitted to remove an element from the collection that is being iterated, it would be a fundamentally useless operation!

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216