Java Reference
In-Depth Information
The nodes of the LinkedList class store two links: one to the next element and one
to the previous one. Such a list is called a doubly linked list. You can use the
previous and hasPrevious methods of the ListIterator interface to move
the iterator position backwards.
The add method adds an object after the iterator, then moves the iterator position
past the new element.
iterator.add("Juliet");
You can visualize insertion to be like typing text in a word processor. Each character
is inserted after the cursor, and then the cursor moves past the inserted character (see
Figure 3 ). Most people never pay much attention to thisÈŒyou may want to try it out
and watch carefully how your word processor inserts characters.
The remove method removes the object that was returned by the last call to next or
previous . For example, the following loop removes all names that fulfill a certain
condition:
while (iterator.hasNext())
{
String name = iterator.next();
if (name fulfills condition)
iterator.remove();
}
You have to be careful when calling remove . It can be called only once after calling
next or previous , and you cannot call it immediately after a call to add . If you
call the method improperly, it throws an IllegalStateException .
Here is a sample program that inserts strings into a list and then iterates through the
list, adding and removing elements. Finally, the entire list is printed. The comments
indicate the iterator position.
ch15/uselist/ListTester.java
1 import java.util.LinkedList;
2 import java.util.ListIterator;
3
4 /**
5 A program that tests the LinkedList class.
Search WWH ::




Custom Search