CKTIS / Java
Iterator — traversing collection elements
Iterator reads collection elements sequentially and, when its optional remove operation is supported, can delete elements during traversal.
Version: Java SE 21; repository runtime, production runtime not attested
Syntax
Iterator<E> it = collection.iterator();
while (it.hasNext()) {
E element = it.next();
// it.remove(); // optional operation
}java.util.Iterator<E> represents a traversal of elements of type E. Iterator.hasNext() checks for another element; Iterator.next() retrieves it and advances the iterator. Once exhausted, next() throws NoSuchElementException.
If the iterator supports removal, Iterator.remove() deletes the last retrieved element. Calling remove() before the first next() call or again without an intervening next() call throws IllegalStateException. Removal is optional: the default implementation of remove() always throws UnsupportedOperationException, even before the first next() call.
The example removes even numbers from an ArrayList through its iterator. Do not add or remove elements directly in the list during this traversal. Its iterators detect such changes on a best-effort basis; ConcurrentModificationException does not guarantee thread safety.
Examples
import java.util.ArrayList;
import java.util.Iterator;
public class Main {
public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(1);
numbers.add(2);
numbers.add(3);
numbers.add(4);
Iterator<Integer> it = numbers.iterator();
while (it.hasNext()) {
int number = it.next();
if (number % 2 == 0) {
it.remove();
}
}
System.out.println(numbers);
}
}Result
[1, 3]
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.