This is a local, edited version of the Collection Interface tutorial from the Java Tutorials; the original page is here.
An
Iterator
is an object that enables you to traverse through a collection and to
remove elements from the collection selectively, if desired. You get an Iterator for a collection by calling its iterator method. The following is the Iterator interface.
public interface Iterator<E> {
boolean hasNext();
E next();
void remove(); //optional
}
The hasNext method returns true if the iteration has more elements, and the next method returns the next element in the iteration. The remove method removes the last element that was returned by next from the underlying Collection. The remove method may be called only once per call to next and throws an exception if this rule is violated.
Note that Iterator.remove is the only safe way to
modify a collection during iteration; the behavior is unspecified if
the underlying collection is modified in any other way while the
iteration is in progress.
Use Iterator instead of the for-each construct when you need to:
for-each construct hides the iterator, so you cannot call remove. Therefore, the for-each construct is not usable for filtering.The following shows you how to use an Iterator to filter a List<Integer> removing negative numbers.
Iterator<Integer> iter = aList.iterator();
while (iter.hasNext())
{
Integer i = iter.next();
if (i < 0)
{
iter.remove();
}
}