Java Reference
In-Depth Information
The
setNext()
method enables the
next
data member to be set for the existing last point in the list when
a new point is added to the list. A reference to the new
ListPoint
object is passed as an argument to the
method. The
getNext()
method enables the next point in the list to be determined, so this method is the
means by which you can iterate through the entire list.
By implementing the
toString()
method for the class, you enable the automatic creation of a
String
representation for a
ListPoint
object when required. Here you differentiate the
String
representation
of the
ListPoint
object by enclosing the
String
representation of
point
between parentheses.
You could now have a first stab at implementing the
PolyLine
class.
TRY IT OUT: The PolyLine Class
You can define the
PolyLine
class to use the
ListPoint
class as follows:
public class PolyLine {
// Construct a polyline from an array of points
public PolyLine(Point[] points) {
if(points != null) {
// Make sure there is an array
for(Point p : points) {
addPoint(p);
}
}
}
// Add a Point object to the list
public void addPoint(Point point) {
ListPoint newEnd = new ListPoint(point);
// Create a new
ListPoint
if(start == null) {
start = newEnd;
// Start is same as
end
} else {
end.setNext(newEnd);
// Set next variable for old end
as new end
}
end = newEnd;
// Store new point
as end
}
// String representation of a polyline
@Override
public String toString() {
StringBuffer str = new StringBuffer("Polyline:");
ListPoint nextPoint = start;
// Set the 1st point
as start
while(nextPoint != null) {