1

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?

7
  • Even if you resolve the ConcurrentModificationException, because of the call to outerIterator.remove(), your ArrayList will be empty at the end of this code. Is this what you want? Commented Jul 16, 2015 at 21:42
  • outerIterator.remove() I used just to check, but yes at the end of looping list will be empty. Commented Jul 16, 2015 at 21:43
  • Then why not simply declare a new empty list of equal size? (or reinitialize this one?) Commented Jul 16, 2015 at 21:45
  • 1
    Something that you can do is use another list to maintain the list of elements to be removed and remove them at the end. Commented Jul 16, 2015 at 21:49
  • 1
    Then please edit your question to remove that line; it changes the entire purpose of the code. Commented Jul 16, 2015 at 21:52

1 Answer 1

1

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 Iterators 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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.