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
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);
}
}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].n goes out of scope and disappears.it.hasNext() to decide whether the loop keeps going.n is created on the stack with the value -2.n < 0 to decide which way the code goes.it.hasNext() to decide whether the loop keeps going.n is created on the stack with the value 8.n goes out of scope and disappears.it.hasNext() to decide whether the loop keeps going.n is created on the stack with the value -1.n < 0 to decide which way the code goes.n goes out of scope and disappears. In the ArrayList that nums points to, .it.hasNext() to decide whether the loop keeps going.[5, 8].Answer: iterator.remove(). Only the iterator knows how to stay valid.
Answer: The next item. hasNext gives the boolean.
← Sets: HashSet and TreeSet · Generic Classes →