Java Reference
In-Depth Information
// Add a point and display the polyline again
polygon.addPoint(10., 10.);
System.out.println(polygon);
// Create Point objects from the coordinate array
Point[] points = new Point[coords.length];
for(int i = 0; i < points.length; i++)
points[i] = new Point(coords[i][0],coords[i][1]);
// Use the points to create a new polyline and display it
PolyLine newPoly = new PolyLine(points);
System.out.println(newPoly);
}
}
Remember that all three classes, Point , ListPoint , and PolyLine need to be together in the same
directory as this class. If you have keyed everything in correctly, the program will output 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 create
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 we 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 linking mechanism. We
might also have lots of other requirements for lists. If we were implementing an address book for instance, we
would want a list of names. A cookery program would need a list of recipes. We might need lists for all kinds
of things - maybe even a list of lists! Let's see if we can do better.
Let's put together a more general purpose linked list, and then use it to store polylines as before. You
should save this in a new directory, as we will implement it as a whole new example.
A General-Purpose Linked List
The key to implementing a general-purpose linked list is the Object class that we discussed earlier in
this chapter. Because the Object class is a superclass of every class, a variable of type Object can be
used to store any kind of object. We could re-implement the ListPoint class in the form of a
ListItem class. This will represent 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
Search WWH ::




Custom Search