wai*_*933 21 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]
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);
Run Code Online (Sandbox Code Playgroud)
为什么会这样?
Cri*_*ian 18
private ArrayList<Point2D.Double> myPolygon = new ArrayList<Point2D.Double>();
Run Code Online (Sandbox Code Playgroud)
che*_*vim 10
确保初始化List:
private List<Point2D.Double> myPolygon = new ArrayList<Point2D.Double>();
Run Code Online (Sandbox Code Playgroud)
另请注意,最好将myPolygon定义为List(接口)而不是ArrayList(实现).