开发者

Java NullPointerException when adding to ArrayList?

开发者 https://www.devze.com 2023-01-20 14:55 出处:网络
My code is throwing a NullPointerException, even though the object seems to properly exist. public class IrregularPolygon {

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 th开发者_如何学JAVAis happening?


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


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消