• 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
  • Ron McLeod
  • Junilu Lacar
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • Jeanne Boyarsky
  • Rob Spoor
  • Bear Bibeault
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Piet Souris
  • Carey Brown
  • Stephan van Hulst
Bartenders:
  • Frits Walraven
  • fred rosenberger
  • salvin francis

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: 13063
281
  • 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
reply
    Bookmark Topic Watch Topic
  • New Topic