Using an ArrayList
We are actually going to be usingArrayList
in two different ways here.
First, notice that a Polyline
can contain an arbitrary number of points,
and these points have to be stored in the Polyline
object.
In order to implement the Polyline
class, we use an ArrayList
to store the points.
You can see
the code for Polyline.java here.
Take a brief look at the relevant parts of the code:
First we declare an ArrayList
of Point
objects:
public class Polyline { private ArrayList<Point> points;
In the constructor, we create the ArrayList
, which
is initially empty.
public Polyline(String givenColor, int givenWidth) { color = givenColor; width = givenWidth; points = new ArrayList<Point>(); }
Then the addPoint
method just has to put the new point at
the end of the list:
public void addPoint(Point point) { points.add(point); }
An ArrayList
is useful here because we don't know in advance, when constructing a Polyline
object, how many points will eventually
be added to it.