代码之家  ›  专栏  ›  技术社区  ›  waiwai933

添加到ArrayList时发生Java NullPointerException?

  •  20
  • waiwai933  · 技术社区  · 14 年前

    我的代码正在抛出一个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 回复  |  直到 13 年前
        1
  •  52
  •   Brad Mace Mike King    14 年前

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

        2
  •  19
  •   Cristian    14 年前
    private ArrayList<Point2D.Double> myPolygon = new ArrayList<Point2D.Double>();
    
        3
  •  11
  •   cherouvim    14 年前

    确保初始化列表:

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