Java Reference
In-Depth Information
}
Directory "TryPolyLine"
Remember that all three classes, Point , ListPoint , and PolyLine , need to be together in the same
folder as this class, which is the TryPolyLine directory if you followed my initial suggestion. If you
have keyed everything in correctly, the program outputs three PolyLine objects:
Polyline: (1.0,1.0) (1.0,2.0) (2.0,3.0) (-3.0,5.0) (-5.0,1.0)
(0.0,0.0)
Polyline: (1.0,1.0) (1.0,2.0) (2.0,3.0) (-3.0,5.0) (-5.0,1.0)
(0.0,0.0) (10.0,10.0)
Polyline: (1.0,1.0) (1.0,2.0) (2.0,3.0) (-3.0,5.0) (-5.0,1.0)
(0.0,0.0)
The first and the third lines of output are the same, with the coordinates from the coords array. The
second has the extra point (10, 10) at the end.
The PolyLine class works well enough but it doesn't seem very satisfactory. Adding all the code to cre-
ate and manage a list for what is essentially a geometric entity is not very object-oriented is it? Come
to think of it, why are you making a list of points? Apart from the type of the data members of the
ListPoint class, there's very little to do with Point objects in its definition; it's all to do with the link-
ing mechanism. You might also have lots of other requirements for lists. If you were implementing an
address book for instance, you would want a list of names. A cookery program would need a list of re-
cipes. You might need lists for all kinds of things — maybe even a list of lists! Let's see if there's a better
approach.
A General-Purpose Linked List
Let's put together a more general-purpose linked list and then use it to store polylines as before. You should
save the source files for this in a new directory, as you implement them as a whole new example. I put the
source files in a directory with the name TryLinkedList in the code download for the topic.
The key to implementing a simple, general-purpose linked list is the Object class discussed earlier in this
chapter. Because the Object class is a superclass of every class, you can use a variable of type Object to
store any kind of object. You could re-implement the ListPoint class in the form of a ListItem class. This
represents an element in a linked list that can reference any type of object:
class ListItem {
// Constructor
public ListItem(Object item) {
this.item = item;
// Store the item
next = null;
// Set next as end point
}
// Return class name & object
@Override
Search WWH ::




Custom Search