简体   繁体   中英

Remove element from ArrayList using ListIterator in loop inside loop

My requirement is to remove from ArrayList like 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 is giving exception

Exception in thread "main" java.util.ConcurrentModificationException

as expected, because I am trying to remove from innerIterator while outerIterator is Iterator on same object(user).

Is there any way to remove element from ArrayList using ListIterator in loop inside loop?

In isolation, calling remove() on an Iterator is the proper way to avoid a ConcurrentModificationException when removing an item from a collection you're iterating. However, you have two Iterator s iterating over the same ArrayList . When you call remove() on innerIterator , outerIterator notices that the list has changed, and it throws a ConcurrentModificationException .

In this case, if SomeOperationOn indicates that the item needs to be removed, then instead of removing it right away, store inner in a temporary List of items to be removed later. After the for loop on the iterators completes, call removeAll passing this temporary list.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM