It is tricky to remove items from a list while within a loop, this is due to the fact that the index and length of the list gets changed.
Given the following list, here are some examples that will give an unexpected result and some that will give the correct result.
List<String> fruits = new ArrayList<String>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Strawberry");
for
statement Skips “Banana”:The code sample will only print Apple
and Strawberry
. Banana
is skipped because it moves to index 0
once Apple
is deleted, but at the same time i
gets incremented to 1
.
for (int i = 0; i < fruits.size(); i++) {
System.out.println (fruits.get(i)); if (“Apple”.equals(fruits.get(i))) { fruits.remove(i); }
}
for
statement Throws Exception:Because of iterating over collection and modifying it at the same time.
Throws: java.util.ConcurrentModificationException
for (String fruit : fruits) {
System.out.println(fruit); if (“Apple”.equals(fruit)) { fruits.remove(fruit); }
}
Iterator
Iterator<String> fruitIterator = fruits.iterator();
while(fruitIterator.hasNext()) {
String fruit = fruitIterator.next();
System.out.println(fruit); if (“Apple”.equals(fruit)) { fruitIterator.remove(); }