• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

enhanced for Question

 
Carlos G�mez
Ranch Hand
Posts: 56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi ranchers,
may someone help me ?

Why when you try to remove an element of a list in a enhanced for, it throws a java.util.ConcurrentModificationException

what is the reason ?

Thanks in advance
 
Henry Wong
author
Marshal
Pie
Posts: 21226
81
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Carlos G�mez:
hi ranchers,
may someone help me ?

Why when you try to remove an element of a list in a enhanced for, it throws a java.util.ConcurrentModificationException

what is the reason ?

Thanks in advance


The problem is *not* the enhanced "for" loop. It is the fact that you are changing the collection while you are iterating through it.

Unfortunately, the enhanced "for" loop hides the iterator from you, so you don't know this is happening. The correct way to remove an item from the collection, while iterating, is to use the iterator to remove the item. However, this means that you can't use the enhanced "for" loop.

Henry
 
Sanjeev Singh
Ranch Hand
Posts: 381
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I got similar exception (java.util.ConcurrentModificationException) today morning when I was writing some code like

So based on what Henry told I concluded is that the invisible iterator is performing the task for getting the objects in Object elem while at the same time in the SOP I am trying to modify the collection(q.poll()).
[ November 23, 2006: Message edited by: Sanjeev Kumar Singh ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic