File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Java in General and the fly likes Removing from a ArrayList while iterating over it Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Removing from a ArrayList while iterating over it" Watch "Removing from a ArrayList while iterating over it" New topic
Author

Removing from a ArrayList while iterating over it

Siamak Saarmann
Ranch Hand

Joined: Aug 21, 2004
Posts: 78
Hello,

I am trying to remove some of the ArrayList during iteration over it. If I call the remove on one of the members I receive "java.util.AbstractList$Itr.checkForComodification" exception.

To avoid this I have added a line of code to repair the iterator (in 2nd code). Is this the right way to achieve my purpose or I should do something else.

Thank you,



Corrected:
Peter Chase
Ranch Hand

Joined: Oct 30, 2001
Posts: 1970
No, you should use the remove() method of Iterator.


Betty Rubble? Well, I would go with Betty... but I'd be thinking of Wilma.
Siamak Saarmann
Ranch Hand

Joined: Aug 21, 2004
Posts: 78
Thank you very much.
Spoon Factorial
Greenhorn

Joined: Dec 23, 2007
Posts: 1
if you need to remove from it often, you should use a LinkedList instead of an ArrayList
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 61448
    
  67

"Spoon Factorial", please check your private messages.


[Asking smart questions] [Bear's FrontMan] [About Bear] [Books by Bear]
 
jQuery in Action, 2nd edition
 
subject: Removing from a ArrayList while iterating over it