Iterating through a Collection avoiding ConcurrentModificationException when removing in loop

0 votes

We all know you can't do this:

for (Object i : l) {
    if (condition(i)) {
        l.remove(i);
    }
}

ConcurrentModificationException etc... this apparently works sometimes, but not always. Here's some specific code:

public static void main(String[] args) {
    Collection<Integer> l = new ArrayList<Integer>();

    for (int i=0; i < 10; ++i) {
        l.add(new Integer(4));
        l.add(new Integer(5));
        l.add(new Integer(6));
    }

    for (Integer i : l) {
        if (i.intValue() == 5) {
            l.remove(i);
        }
    }

    System.out.println(l);
}

This, of course, results in:

Exception in thread "main" java.util.ConcurrentModificationException

... even though multiple threads aren't doing it... Anyway.

What's the best solution to this problem? How can I remove an item from the collection in a loop without throwing this exception?

I'm also using an arbitrary Collection here, not necessarily an ArrayList, so you can't rely on get.

Jul 3, 2018 in Java by developer_1
• 3,320 points
1,145 views

1 answer to this question.

0 votes

You can either use the iterator directly like you mentioned, or else keep a second collection and add each item you want to remove to the new collection, then removeAll at the end. This allows you to keep using the type-safety of the for-each loop at the cost of increased memory use and cpu time (shouldn't be a huge problem unless you have really, really big lists or a really old computer)

public static void main(String[] args)
{
    Collection<Integer> l = new ArrayList<Integer>();
    Collection<Integer> itemsToRemove = new ArrayList<Integer>();
    for (int i=0; i < 10; ++i) {
    l.add(new Integer(4));
    l.add(new Integer(5));
    l.add(new Integer(6));
    }
    for (Integer i : l)
    {
        if (i.intValue() == 5)
            itemsToRemove.add(i);
    }

    l.removeAll(itemsToRemove);
    System.out.println(l);
}
answered Jul 3, 2018 by Rishabh
• 3,620 points

Related Questions In Java

0 votes
0 answers
0 votes
2 answers

How can I invoke a method when the method name is in the form of a given string?

You could probably use method invocation from reflection: Class<?> ...READ MORE

answered Aug 19, 2019 in Java by Sirajul
• 59,230 points
2,588 views
0 votes
2 answers

What is the easiest way to iterate through the characters of a string in Java?

There are two approaches to this: for(int i ...READ MORE

answered Aug 19, 2019 in Java by Sirajul
• 59,230 points
1,501 views
0 votes
1 answer

What is the array initialization syntax when not in a declaration?

Probably you'd have to ask the Java ...READ MORE

answered Jul 13, 2018 in Java by Akrati
• 3,190 points
383 views
0 votes
1 answer

What is ArrayIndexOutOfBoundsException ?

If You check System.out.print(names.length); you will get 3 ...READ MORE

answered May 11, 2018 in Java by sharth
• 3,370 points
771 views
0 votes
1 answer

How can we resolve ClassNotFoundException in Java?

Your classpath is broken. Depending on how you ...READ MORE

answered May 22, 2018 in Java by Akrati
• 3,190 points
1,012 views
0 votes
1 answer

How to resolve the java.net.ConnectException in Java?

If you are getting java.net.ConnectionException, it means ...READ MORE

answered Jun 4, 2018 in Java by Akrati
• 3,190 points
1,971 views
+1 vote
1 answer

How can we resolve java.lang.OutOfMemoryError in Java?

Work with smaller batches of HashMap Objects ...READ MORE

answered Jun 5, 2018 in Java by sharth
• 3,370 points
827 views
0 votes
1 answer

How to divide a string in two parts

String s="yourstring"; boolean flag = true; for(int i=0;i<s.length();i++) { ...READ MORE

answered Apr 13, 2018 in Java by Rishabh
• 3,620 points
921 views
0 votes
2 answers

Counting no of Occurrence of a particular character inside a string in Java

We can find out the no. of ...READ MORE

answered Sep 7, 2018 in Java by Sushmita
• 6,910 points
2,309 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP