当向ArrayList添加元素时,Java出现空指针异常(NullPointerException)?

24

尽管对象似乎存在,但我的代码仍然抛出了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);

为什么会发生这种情况?

3个回答

55

根据您提供的代码部分,看起来您没有初始化myPolygon


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

12

确保您初始化List:

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

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


这还是真的吗?我不这么认为,因为如果你将其初始化为 ArrayList,那么你就不需要在参数的另一侧指定类型了。 - Ajay
1
我可以知道为什么吗?有什么优势吗?:“还要注意,最好将myPolygon定义为List(接口),而不是ArrayList(实现)”。 - FullStackDeveloper

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接