Exception Handling ConcurrentModificationException while removing elements from ArrayList while iterating it

0 votes

I'm trying to remove some elements from an ArrayList while iterating it like this:

for (String str : myArrayList) {
    if (someCondition) {
        myArrayList.remove(str);
    }
}

I am getting a ConcurrentModificationException when trying to remove items from the list at the same time when iterating myArrayList. Is there some simple solution to solve this problem?

Jan 10, 2019 in Java by Daisy
• 8,120 points
582 views

1 answer to this question.

0 votes
Iterator<String> iter = myArrayList.iterator();

while (iter.hasNext()) {
    String str = iter.next();

    if (someCondition)
        iter.remove();
}
answered Jan 10, 2019 by Sushmita
• 6,910 points

Related Questions In Java

0 votes
0 answers
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

Is it possible to run a java program from command line on windows?How?

  Let's say your file is in C:\myprogram\ Run ...READ MORE

answered Apr 18, 2018 in Java by sophia
• 1,400 points
2,376 views
+1 vote
1 answer

Remove objects from an array in Java?

We can use external libraries: org.apache.commons.lang.ArrayUtils.remove(java.lang.Object[] array, int ...READ MORE

answered Jun 26, 2018 in Java by scarlett
• 1,290 points
980 views
0 votes
2 answers

what is the best way to convert an ArrayList to a String

You could probably use the Joiner class ...READ MORE

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

Sorting an ArrayList in Java

You can easily do this by simply ...READ MORE

answered May 5, 2018 in Java by geek.erkami
• 2,680 points
1,951 views
+1 vote
1 answer

Are arrays equivalent to objects in Java ?

Yes; the Java Language Specification writes: In the Java ...READ MORE

answered May 10, 2018 in Java by Rishabh
• 3,620 points
1,029 views
0 votes
2 answers

Remove duplicate elements from an ArrayList in Java

List<String> al = new ArrayList<>(); // add elements ...READ MORE

answered Jul 26, 2018 in Java by Sushmita
• 6,910 points
1,250 views
0 votes
3 answers

Is it possible to take char input from scanner?

// Use a BufferedReader to read characters ...READ MORE

answered Sep 7, 2018 in Java by Daisy
• 8,120 points
8,561 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