aspose file tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes ConcurrentModificationException and for loops Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Reply Bookmark "ConcurrentModificationException and for loops" Watch "ConcurrentModificationException and for loops" New topic
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
I perfectly understand as ConcurrentModificationException is thrown when a thread iterating over it AND modifying it.


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
    
    1

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
 
I agree. Here's the link: http://zeroturnaround.com/jrebel - it saves me about five hours per week
 
subject: ConcurrentModificationException and for loops
 
Similar Threads
Offer VS add
PriorityQueue()
Print contents of PriorityQueue not working
PriorityQueue