Java Reference
In-Depth Information
You might also want to create a
PolyLine
object from an array of coordinates. The constructor to do
this would be:
// Construct a polyline from an array of coordinates
public PolyLine(double[][] coords) {
if(coords != null) {
// Create a one point list
start = new ListPoint(new Point(coords[0][0], coords[0][1]));
// First is start
end = start; // as well as end
// Now add the other points
for(int i = 1; i < coords.length ; i++)
addPoint(coords[i][0], coords[i][1]);
}
}
How It Works
The
PolyLine
class has the data members
start
and
end
that we saw in the diagram. These will
reference the first and last points of the list, or
null
if the list is empty. Storing the end point in the list
is not essential since we could always find it by going through the list starting with start. However,
having a reference to the last point saves a lot of time when we want to add a point to the list. The
constructor accepts an array of
Point
objects and starts the process of assembling the object, by
creating a list containing one
ListPoint
object produced from the first element in the array. It then
uses the
addPoint()
method to add all the remaining points in the array to the list.
Adding a point to the list is deceptively simple. All the
addPoint()
method does is create a
ListPoint
object from the
Point
object passed as an argument, sets the
next
member of the old end
point in the list to refer to the new point and finally stores a reference to the new end point in the
member
end
.
The method
toString()
will return a string representing the
PolyLine
object as a list of point
coordinates. Note how the
next
member of the
ListPoint
objects controls the loop that runs through
the list. When the last
ListPoint
object is reached, the
next
member will be returned as
null
, and
the
while
loop will end. We can now give the
PolyLine
class a whirl.
Try It Out - Using
PolyLine
Objects
We can create a simple example to illustrate how to use the
PolyLine
class:
public class TryPolyLine {
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);