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 iterators 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

Popular posts from this blog

c# - Better 64-bit byte array hash -

webrtc - Which ICE candidate am I using and why? -

php - Zend Framework / Skeleton-Application / Composer install issue -