'why it showing ConcurrentModificationException? arraylist want delete some element by specific condition [duplicate]
I try to run this sample program but fail in the console and pop up -
Exception in thread "main" java.util.ConcurrentModificationException
What it purpose is create arraylist, add some string then delete string start with "A" in the arraylist.
here is code:
List<String> dryFruits = new ArrayList<();
dryFruits.add("Walnut");
dryFruits.add("Apricot");
dryFruits.add("Almond");
dryFruits.add("Date");
Iterator<String> iterator = dryFruits.iterator();
while(iterator.hasNext()) {
String dryFruit = iterator.next();
if(dryFruit.startsWith("A")) {
dryFruits.remove(dryFruit);
}
}
System.out.println(dryFruits);
I expecting print out [Walnut, Date] only.
Solution 1:[1]
Exception said that: This exception may be thrown by methods that have detected concurrent modification of an object when such modification is not permissible. You changed contains of iterated List, I can suggest as follow resolve:
List<String> dryFruits = new ArrayList<>();
List<String> result = new ArrayList<>();
dryFruits.add("Walnut");
dryFruits.add("Apricot");
dryFruits.add("Almond");
dryFruits.add("Date");
Iterator<String> iterator = dryFruits.iterator();
while(iterator.hasNext()) {
String dryFruit = iterator.next();
if(!dryFruit.startsWith("A")) {
result.add(dryFruit);
}
}
System.out.println(result);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
