Java Reference
In-Depth Information
// Add a point from a coordinate pair to the list
public void addPoint(double x, double y) {
polyline.addItem(new Point(x, y)); // Add the point to
the list
}
// String representation of a polyline
@Override
public String toString() {
StringBuffer str = new StringBuffer("Polyline:");
Point point = polyline.getFirst();
// Set the 1st point
as start
while(point != null) {
str.append(" (" + point + ")"); // Append the current
point
point = polyline.getNext();
// Make the next point
current
}
return str.toString();
}
private LinkedList<Point> polyline;
// The linked list of
points
}
Directory "TryGenericLinkedList"
I have bolded all the lines that have been changed from the original version — yes, all five of them!
Two of the changes remove now redundant casts to type Point . The constructor calls that create objects
implementing a linked list now use the LinkedList<T> generic type. I use the diamond operator so the
compiler infers that the type argument is Point because polyline is now of type LinkedList<Point> .
Put this source file in a directory along with the Point class source file that you created in Chapter 6 and
the source file containing the LinkedList<> generic type. You can then add the following source file
that tries out the new version of the PolyLine class:
public class TryGenericLinkedList {
public static void main(String[] args) {
// Create an array of coordinate pairs
double[][] coords = { {1, 1}, {1, 2}, { 2, 3},
{-3, 5}, {-5, 1}, {0, 0} };
// Create a polyline from the coordinates and display it
PolyLine polygon = new PolyLine(coords);
System.out.println(polygon);
// Add a point and display the polyline again
polygon.addPoint(10, 10);
Search WWH ::




Custom Search