Java Reference
In-Depth Information
public void addItem(Object item) {
ListItem newEnd = new ListItem(item);
// Create a new ListItem
if(start == null) {
// Is the list empty?
start = end = newEnd;
// Yes, so new element is start and end
} else {
// No, so append new element
end.next = newEnd;
// Set next variable for old end
end = newEnd;
// Store new item as end
}
}
// Get the first object in the list
public Object getFirst() {
current = start;
return start == null ? null : start.item;
}
// Get the next object in the list
public Object getNext() {
if(current != null) {
current = current.next;
// Get the reference to the next item
}
return current == null ? null : current.item;
}
private ListItem start = null;
// First ListItem in the list
private ListItem end = null;
// Last ListItem in the list
private ListItem current = null;
// The current item for iterating
// ListItem as a nested class
private class ListItem {
// ListItem class definition as before...
}
}
Directory "TryPolyLine2"
Save this source file in the new directory for the example. You can use this class to create a linked list
containing any types of objects. The class has data members to track the first and last items in the list, plus
the member current , which is used to iterate through the list. You have three class constructors. The default
constructor creates an empty list. You have a constructor to create a list with a single object, and another
to create a list from an array of objects. Any list can also be extended by means of the addItem() method.
Each of the constructors, apart from the default, sets the current member to the first item in the list, so if
the list is not empty, this refers to a valid first item.
You can see that because the ListItem class is a member of the LinkedList class, you can refer to its
data members directly within methods in the LinkedList class. This obviates the need for any methods in
the ListItem class to get or set its fields. Because it is private it is not accessible outside the LinkedList
class so there is no risk associated with this — as long as you code the LinkedList class correctly, of course.
The addItem() method works in much the same way as the addPoint() method did in the PolyLine
class. It creates a new ListItem object and updates the next member of the previous last item to refer to the
new one. The complication is the possibility that the list might be empty. The check in the if takes care of
this. You take special steps if start holds a null reference.
Search WWH ::




Custom Search