Java Reference
In-Depth Information
public String toString() {
return "ListItem " + item ;
}
ListItem next;
// Refers to next item in the list
Object item;
// The item for this ListItem
}
Directory "TryPolyLine2"
It's basically similar to the ListPoint class except that you have omitted the methods to set and retrieve
the next member reference. You see why these are not necessary in a moment. The toString() method as-
sumes that the object referenced by item implements a toString() method. You won't use the toString()
method here when you come to exercise the general linked list class you're implementing, but it is a good
idea to implement the toString() method for your classes anyway. If you do, meaningful representations
of class objects can always be output using the println() method, which is very handy for debugging.
You can now use objects of this class in a definition of a class that represents a linked list.
Defining a Linked List Class
The mechanics of creating and handling the linked list is similar to what you had in the PolyLine class, but
externally you need to deal in the objects that are stored in the list, not in terms of ListItem objects. In fact,
you don't need to have the ListItem class separate from the LinkedList class. You can make it an inner
class:
public class LinkedList {
// Default constructor - creates an empty list
public LinkedList() {}
// Constructor to create a list containing one object
public LinkedList(Object item) {
if(item != null) {
current = end = start = new ListItem(item); // item is the start and end
}
}
// Construct a linked list from an array of objects
public LinkedList(Object[] items) {
if(items != null) {
// Add the items to the list
for(Object item : items) {
addItem(item);
}
current = start;
}
}
// Add an item object to the list
Search WWH ::




Custom Search