• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

ConcurrentModificationException and for loops

 
Ranch Hand
Posts: 384
MyEclipse IDE Spring Java
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
 
Ranch Hand
Posts: 287
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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
 
Saloon Keeper
Posts: 15510
363
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Posts: 384
MyEclipse IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
i mistaken foreach() loop as a normal for() loop. .
Thanks for clearing this.



Regards
naveen
 
This is my favorite tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic