24

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?

3 Answers 3

55

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

12

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).

2 Comments

Is this still true? I don't think so, because if you initialise it as an ArrayList then you do not need to specify a type on the other side of the argument anymore.
May I know why? What is the advantage?: "Also note that it's best to define myPolygon as a List (interface) and not ArrayList (implementation)"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.