Java Reference
In-Depth Information
You also have to be careful to call the equals method for comparisons.
The code involves ordinary list operations that you've seen throughout this
chapter:
public int indexOf(E value) {
int index = 0;
ListNode<E> current = front.next;
while (current != back) {
if (current.data.equals(value)) {
return index;
}
index++;
current = current.next;
}
return -1;
}
Many of the methods that you wrote for LinkedIntList can be used with only
slight modifications for the LinkedList . Let's look at remove as an example.
Because of the dummy nodes, you don't have to make a special case for an empty
list. But because of the doubly linking, you have to reset two links (a next and a
prev ) when you remove the node:
public void remove(int index) {
checkIndex(index);
ListNode<E> current = gotoIndex(index - 1);
current.next = current.next.next;
current.next.prev = current;
size--;
}
You'll want to make similar changes to the add method.
The LinkedList class includes one final improvement. Instead of keeping the
node class as a separate class, the LinkedList class includes it as a nested class.
In this case, the individual node objects don't need access to the outer object, so it
is best to declare the class to be a static inner class. The details of this code are
beyond the scope of this topic, but the quick explanation is that providing access
to the outer class takes some extra storage and because we're likely to construct
thousands and perhaps even millions of node objects, we want to be more efficient
about the space that they take up. Declaring the class to be static accomplishes
that goal.
The complete code for the LinkedList class can be found at http://
buildingjavaprograms.com. You will also find the List interface and an updated
version of ArrayList there.
 
Search WWH ::




Custom Search