我的代码抛出了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);
为什么会这样?
答案 0 :(得分:50)
根据您提供的代码部分,看起来您尚未初始化myPolygon
答案 1 :(得分:18)
private ArrayList<Point2D.Double> myPolygon = new ArrayList<Point2D.Double>();
答案 2 :(得分:10)
确保初始化列表:
private List<Point2D.Double> myPolygon = new ArrayList<Point2D.Double>();
另请注意,最好将myPolygon定义为List(接口)而不是ArrayList(实现)。