Iterators: Removing While Looping

Removing from a list inside a for-each loop crashes. An Iterator lets you remove the current item safely.

Java · intermediate · 7 min · 23 steps · free

What you'll learn

IteratorDemo.java

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class IteratorDemo {
    public static void main(String[] args) {
        List<Integer> nums = new ArrayList<>(List.of(5, -2, 8, -1));
        Iterator<Integer> it = nums.iterator();
        while (it.hasNext()) {
            int n = it.next();
            if (n < 0) {
                it.remove();            // safe removal while looping
            }
        }
        System.out.println(nums);
    }
}

Step by step

  1. The program starts in main. args holds its command-line arguments (none here). nums is created on the stack and points to a new ArrayList on the heap: [5, -2, 8, -1].
  2. An iterator: a cursor that walks through the list.
  3. hasNext: is there another item?
  4. next() moves the cursor and returns 5.
  5. n goes out of scope and disappears.
  6. The end of this block is reached.
  7. Java checks it.hasNext() to decide whether the loop keeps going.
  8. n is created on the stack with the value -2.
  9. Java checks n < 0 to decide which way the code goes.
  10. -2 is negative: it.remove() deletes the item just returned, safely.
  11. The end of this block is reached.
  12. Java checks it.hasNext() to decide whether the loop keeps going.
  13. n is created on the stack with the value 8.
  14. n goes out of scope and disappears.
  15. The end of this block is reached.
  16. Java checks it.hasNext() to decide whether the loop keeps going.
  17. n is created on the stack with the value -1.
  18. Java checks n < 0 to decide which way the code goes.
  19. n goes out of scope and disappears. In the ArrayList that nums points to, .
  20. The end of this block is reached.
  21. Java checks it.hasNext() to decide whether the loop keeps going.
  22. It prints [5, 8].
  23. [5, 8]: both negatives removed during one pass, without errors.

Common mistakes

Best practices

Key takeaways

Check yourself

Which removes safely while iterating?

Answer: iterator.remove(). Only the iterator knows how to stay valid.

What does next() return?

Answer: The next item. hasNext gives the boolean.

·

More in The Collections Framework