[!NOTE] Have you ever tried to loop through an
ArrayListof 10 items using a standardfor-eachloop, and attempted to.remove()an item inside the loop if it met a certain condition?
If you do this, your application will violently crash with a ConcurrentModificationException.
Java does not allow you to modify the size of a collection while an advanced for-each loop is actively traversing it. It breaks the internal memory pointer logic of the loop!
The Iterator Object
To safely loop through a collection while actively deleting elements from it, you must use an Iterator.
An Iterator is an object that can be used to loop through collections, like ArrayList and HashSet. It acts like a cursor hovering right before the first element.
import java.util.ArrayList;
import java.util.Iterator;
public class Main {
public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<Integer>();
numbers.add(12);
numbers.add(8);
numbers.add(2);
numbers.add(23);
// 1. We summon an Iterator linked directly to our collection
Iterator<Integer> it = numbers.iterator();
// 2. We use a while-loop. .hasNext() checks if there is another item available!
while(it.hasNext()) {
// 3. .next() physically grabs the item and moves the cursor forward
Integer i = it.next();
// 4. If the number is less than 10, we delete it safely!
if(i < 10) {
it.remove(); // Safely deletes 8 and 2!
}
}
System.out.println(numbers); // Output: [12, 23]
}
}
When to use standard loops vs Iterators?
- Use a standard
forloop if modifying sizes and you don't mind manually adjusting theicounter backwards. - Use a clean
for-eachloop if you are just Reading data or printing values sequentially. This is 95% of use cases. - Use a
while(iterator.hasNext())if you are executing intensive filter checks and actively deleting invalid data.
[!TIP] With the introduction of Java 8 Streams, explicit Iterator writing has become much rarer. You can now use
numbers.removeIf(i -> i < 10);in a single elegant line of code! But understanding the Iterator mechanics is a mandatory interview question.