添加到ArrayList时Java NullPointerException?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3949926/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 07:26:42  来源:igfitidea点击:

Java NullPointerException when adding to ArrayList?

javaarraylistnullpointerexception

提问by waiwai933

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

我的代码抛出 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);

Why is this happening?

为什么会这样?

采纳答案by Brad Mace

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

根据您提供的代码部分,您似乎尚未初始化 myPolygon

回答by Cristian

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

回答by cherouvim

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

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