java - Remove element from ArrayList using ListIterator in loop inside loop -
my requirement remove arraylist this:
arraylist<user> user = new arraylist<user>(); listiterator<user> outeriterator = null; listiterator<user> inneriterator = null; user outer = null; user inner = null; for(outeriterator = user.listiterator(); outeriterator.hasnext();) { outer = outeriterator.next(); for(inneriterator = user.listiterator(); inneriterator.hasnext();) { inner = inneriterator.next(); if(someoperationon(outer,inner)) { inneriterator.remove(); } } }
above code giving exception
exception in thread "main" java.util.concurrentmodificationexception
as expected, because trying remove inneriterator while outeriterator iterator on same object(user).
is there way remove element arraylist using listiterator in loop inside loop?
in isolation, calling remove()
on iterator
proper way avoid concurrentmodificationexception
when removing item collection you're iterating. however, have two iterator
s iterating on same arraylist
. when call remove()
on inneriterator
, outeriterator
notices list has changed, , throws concurrentmodificationexception
.
in case, if someoperationon
indicates item needs removed, instead of removing right away, store inner
in temporary list
of items removed later. after for
loop on iterators completes, call removeall
passing temporary list.
Comments
Post a Comment