This week's book giveaway is in the Java 8 forum.
We're giving away four copies of Java 8 in Action and have Raoul-Gabriel Urma, Mario Fusco, and Alan Mycroft on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes enhanced for Question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "enhanced for Question" Watch "enhanced for Question" New topic
Author

enhanced for Question

Carlos G�mez
Ranch Hand

Joined: Sep 06, 2006
Posts: 56
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
Sheriff

Joined: Sep 28, 2004
Posts: 18136
    
  39

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


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Sanjeev Singh
Ranch Hand

Joined: Nov 01, 2006
Posts: 381
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 ]

~Sanjeev Singh<br />SCJP 1.5
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: enhanced for Question
 
Similar Threads
intersting
Extended for loop
Array reverse
Enhanced for loops
Enhanced for loop - new to Java 5 or Java 6?