Java Reference
In-Depth Information
// Construct a polyline from an array of coordinate
public PolyLine(double[][] coords) {
// Add the points
for(int i = 0; i < coords.length; i++)
polyline.add(new Point(coords[i][0], coords[i][1]));
}
// Add a Point object to the list
public void addPoint(Point point) {
polyline.add(point); // Add the new point
}
// Add a point to the list
public void addPoint(double x, double y) {
polyline.add(new Point(x, y));
}
// String representation of a polyline
public String toString() {
StringBuffer str = new StringBuffer("Polyline:");
Iterator points = polyline.iterator(); // Get an iterator
while(points.hasNext())
str.append(" "+ (Point)points.next()); // Append the current point
return str.toString();
}
private LinkedList polyline = new LinkedList(); // Stores points for polyline
}
The class is a lot simpler because the
LinkedList
class provides all the mechanics of operating a
linked list. Since the interface to the
PolyLine
class is the same as the previous version, the original
version of
main()
will run unchanged and produce exactly the same output.
How It Works
The only interesting bit is the change to the
PolyLine
class.
Point
objects are now stored in the linked list
implemented by the
LinkedList
object,
polyline
. We use the
add()
method to add points in the
constructors and the
addPoint()
methods. The
toString()
method now uses an iterator to go through
the points in the list. Using a collection class makes the
PolyLine
class very straightforward.
Using Maps
As we saw at the beginning of this chapter, a
map
is a way of storing data that minimizes the need for
searching when you want to retrieve an object. Each object is associated with a key that is used to
determine where to store the reference to the object, and both the key and the object are stored in the
map. Given a key, you can always go more or less directly to the object that has been stored in the map
based on the key. It's important to understand a bit more about how the storage mechanism works for a
map, and in particular what the implications of using the default hashing process are. We will explore
the use of maps primarily in the context of the
HashMap
class.