Java Reference
In-Depth Information
loop and letting Java manage the iterator for you. This technique greatly simplifies
the code:
public void addAll(List<E> other) {
for (E value : other) {
add(value);
}
}
You should use this same implementation for the method in the ArrayList class
to make sure that it also runs efficiently for all types of lists. It turns out that several
of the methods can be implemented using the same code for both the array list and
linked list. A better implementation would introduce an abstract list superclass to rep-
resent this similarity. This is left as a programming project idea.
Other Code Details
We are almost ready to put the pieces together. But first, let's consider the fields for
our LinkedList class. We have already discussed keeping track of both the front and
the back of the list. It is also useful to keep track of the current size in a field so that
you don't have to traverse the list to find out its size. So there will be three fields:
public class LinkedList<E> implements List<E> {
private ListNode<E> front; // first value in the list
private ListNode<E> back; // last value in the list
private int size; // current number of elements
...
}
To initialize the list, you want to construct the two dummy nodes and then set up
everything to refer to an empty list. You also have to implement the clear method
that is supposed to return to an empty list, so this is a good opportunity to write the
code once in the clear method and to have the constructor call it. The constructor
will look like this:
public LinkedList() {
front = new ListNode<E>(null);
back = new ListNode<E>(null);
clear();
}
Notice that you need to include the type parameter <E> when you construct the
nodes. For the clear method, you simply make these two dummy nodes point to
each other and reset the size:
public void clear() {
front.next = back;
 
Search WWH ::




Custom Search