| Author |
ConcurrentModificationException and for loops
|
naveen yadav
Ranch Hand
Joined: Oct 23, 2011
Posts: 380
|
|
For given code
The following code does not throw ConcurrentModificationException and run fine , I perfectly understand as ConcurrentModificationException is thrown when a thread iterating over it AND modifying it.
By iterating I means specifically using Iterator not using for loops
But here , it throws ConcurrentModificationException. I dont know why ?
Regards
naveen
|
 |
Harsha Smith
Ranch Hand
Joined: Jul 18, 2011
Posts: 287
|
|
using enhanced for loop...you are iterating through the collection and by calling poll(), you are modifying it. And yes priority queue is a collection
|
 |
Stephan van Hulst
Bartender
Joined: Sep 20, 2010
Posts: 3050
|
|
Harsha is correct. The enhanced for loop can only be used on arrays and subtypes of Iterable. The enhanced for loop will use the iterator to iterate through all the elements, so it's always a bad idea to remove elements from a collection using an enhanced for loop. Instead, you should use the normal for-loop, with the iterator:
|
 |
naveen yadav
Ranch Hand
Joined: Oct 23, 2011
Posts: 380
|
|
i mistaken foreach() loop as a normal for() loop. .
Thanks for clearing this.
Regards
naveen
|
 |
 |
|
|
subject: ConcurrentModificationException and for loops
|
|
|