java - Iterating through a Collection, avoiding ConcurrentModificationException when removing in loop -
we know can't this:
for (object : l) { if (condition(i)) { l.remove(i); } }
concurrentmodificationexception
etc... apparently works sometimes, not always. here's specific code:
public static void main(string[] args) { collection<integer> l = new arraylist<integer>(); (int i=0; < 10; ++i) { l.add(new integer(4)); l.add(new integer(5)); l.add(new integer(6)); } (integer : l) { if (i.intvalue() == 5) { l.remove(i); } } system.out.println(l); }
this, of course, results in:
exception in thread "main" java.util.concurrentmodificationexception
... though multiple threads aren't doing it... anyway.
what's best solution problem? how can remove item collection in loop without throwing exception?
i'm using arbitrary collection
here, not arraylist
, can't rely on get
.
iterator.remove()
safe, can use this:
list<string> list = new arraylist<>(); // clever way create iterator , call iterator.hasnext() // in while-loop. same doing: // iterator<string> iterator = list.iterator(); // while (iterator.hasnext()) { (iterator<string> iterator = list.iterator(); iterator.hasnext();) { string string = iterator.next(); if (string.isempty()) { // remove current element iterator , list. iterator.remove(); } }
note iterator.remove
safe way modify collection during iteration; behavior unspecified if underlying collection modified in other way while iteration in progress.
source:
http://docs.oracle.com/javase/tutorial/collections/interfaces/collection.html
and similarly, if have listiterator
, want add items, can use listiterator#add
, same reason can use iterator#remove
— it's designed allow it.
Comments
Post a Comment