My code is throwing a NullPointerException, even though the object seems to properly exist.

public class IrregularPolygon {

    private ArrayList<Point2D.Double> myPolygon;

    public void add(Point2D.Double aPoint) {
        System.out.println(aPoint); // Outputs Point2D.Double[20.0, 10.0]
        myPolygon.add(aPoint); // NullPointerException gets thrown here
    }
}

// Everything below this line is called by main()

    IrregularPolygon poly = new IrregularPolygon();
    Point2D.Double a = new Point2D.Double(20,10);
    poly.add(a);

Why is this happening?

link|improve this question

feedback

3 Answers

up vote 7 down vote accepted

based on the parts of the code you provided, it looks like you haven't initialized myPolygon

link|improve this answer
feedback
private ArrayList<Point2D.Double> myPolygon = new ArrayList<Point2D.Double>();
link|improve this answer
feedback

Make sure you initialize the List:

private List<Point2D.Double> myPolygon = new ArrayList<Point2D.Double>();

Also note that it's best to define myPolygon as a List (interface) and not ArrayList (implementation).

link|improve this answer
feedback

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.