An Iterator is an object that enables traversal through a collection, one element at a time. It provides methods to access and remove elements during iteration.
While Iterator allows unidirectional traversal, ListIterator supports bidirectional traversal and additional functionalities like adding elements and obtaining indexes.
To use an Iterator, first create one from the ArrayList:
Iterator<String> iterator = names.iterator();
Using the Iterator to traverse elements:
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
hasNext(): Returns true if there are more elements.next(): Returns the next element.remove(): Removes the last element returned by next().Iterator<String> iterator = names.iterator();
while (iterator.hasNext()) {
String name = iterator.next();
System.out.println(name);
}
ListIterator offers additional features like: