添加到ArrayList时出现Java NullPointerException?

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

public class IrregularPolygon { private ArrayList 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); 

为什么会这样?

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

 private ArrayList myPolygon = new ArrayList(); 

确保初始化List:

 private List myPolygon = new ArrayList(); 

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