Java Reference
In-Depth Information
LinkedList<String> employeeNames = . . .;
ListIterator<String> iterator =
employeeNames.listIterator();
Note that the iterator class is also a generic type. A
ListIterator<String>
iterates through a list of strings; a
ListIterator<Product>
visits the elements
in a
LinkedList<Product>
.
Initially, the iterator points before the first element. You can move the iterator
position with the
next
method:
iterator.next();
The
next
method throws a
NoSuchElementException
if you are already past
the end of the list. You should always call the method
hasNext
before calling
next
Ȍit returns
true
if there is a next element.
if (iterator.hasNext())
iterator.next();
The
next
method returns the element that the iterator is passing. When you use a
ListIterator<String>
, the return type of the
next
method is
String
. In
general, the return type of the
next
method matches the type parameter.
You traverse all elements in a linked list of strings with the following loop:
while (iterator.hasNext())
{
String name = iterator.next();
Do something with name
}
As a shorthand, if your loop simply visits all elements of the linked list, you can use
the Ȓfor eachȓ loop:
668
669
for (String name : employeeNames)
{
Do something with name
}
Then you don't have to worry about iterators at all. Behind the scenes, the
for
loop
uses an iterator to visit all list elements (see
Advanced Topic 15.1
).