添加到ArrayList时出现Java NullPointerException?

添加到ArrayList时出现Java NullPointerException?,java,arraylist,nullpointerexception,Java,Arraylist,Nullpointerexception,我的代码抛出了一个NullPointerException,即使该对象似乎正确存在 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]

我的代码抛出了一个NullPointerException,即使该对象似乎正确存在

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);
公共类{
私有数组列表;
公共void添加(Point2D.Double aPoint){
System.out.println(aPoint);//输出点2d.Double[20.0,10.0]
myPolygon.add(aPoint);//此处抛出NullPointerException
}
}
//这行下面的所有内容都由main()调用
不规则多边形多边形=新的不规则多边形();
Point2D.Double a=新的Point2D.Double(20,10);
加入(a);

为什么会发生这种情况?

根据您提供的部分代码,您似乎尚未初始化
myPolygon
private ArrayList myPolygon=new ArrayList();
private ArrayList<Point2D.Double> myPolygon = new ArrayList<Point2D.Double>();

确保初始化列表:

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

还请注意,最好将myPolygon定义为列表(接口),而不是ArrayList(实现)。

这仍然正确吗?我不这么认为,因为如果您将它初始化为
ArrayList
,那么您就不需要在参数的另一端指定类型了。我可以知道为什么吗?优点是什么?:“还要注意,最好将myPolygon定义为列表(接口),而不是ArrayList(实现)”