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 in Java by Daisy
• 8,050 points
46 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 by Sushmita
• 6,880 points

Related Questions In Java

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
210 views
0 votes
2 answers
0 votes
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,280 points
74 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 in Java by Sirajul
• 41,000 points
82 views
0 votes
1 answer

Sorting an ArrayList in Java

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

answered May 4, 2018 in Java by geek.erkami
• 2,640 points
243 views
0 votes
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,540 points
81 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,880 points
168 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,050 points
2,227 views