向ArrayList添加元素时出现NullPointerException

Gra*_*ick 2 java processing

我正在尝试使用以下命令向我的ArrayList添加名为activList的元素:

activList.add(new Fiducial(iD, x, y ));
Run Code Online (Sandbox Code Playgroud)

但是在运行代码时,我在这一行得到一个NullPointerException:

int cols = 10, rows = 10;
int rectangleWidth = 100;
int rectangleHeight = 60;

// these are some helper variables which are used
// to create scalable graphical feedback
int k, l, iD;
float cursor_size = 15;
float object_size = 60;
float table_size = 760;
float scale_factor = 1;
float x, y;

ArrayList<Fiducial> activList  ;


public class Fiducial {
  public int iD;
  public float x;
  public float y;

  public Fiducial(int iD, float x, float y) {
    this.iD = iD;
    this.x = x;
    this.y = y;
  }
}


void draw() {
  // Begin loop for columns
  for ( k = 0; k < cols; k++) {
    // Begin loop for rows
    for ( l = 0; l < rows; l++) {
      fill(255);
      stroke(0);
      rect(k*rectangleWidth, l*rectangleHeight, rectangleWidth, rectangleHeight);
    }
  }


  // This part detects the fiducial markers 
  float obj_size = object_size*scale_factor; 
  float cur_size = cursor_size*scale_factor; 

  ArrayList<TuioObject> tuioObjectList = tuioClient.getTuioObjectList();
  for (int i=0; i<tuioObjectList.size (); i++) {
    TuioObject tobj= tuioObjectList.get(i);
    stroke(0);
    fill(0, 0, 0);
    pushMatrix();
    translate(tobj.getScreenX(width), tobj.getScreenY(height));
    rotate(tobj.getAngle());
    rect(-80, -40, 80, 40);
    popMatrix();
    fill(255);
    x = round(10*tobj.getX ());
    y = round(10*tobj.getY ());
    iD = tobj.getSymbolID();
    activList.add(new Fiducial(iD, x, y ));
    fiducialCoordinates ();
  }
}


void fiducialCoordinates () {
  System.out.println("x= "+ x + " y= " + y + " iD= " + iD );
  System.out.println(activList);
}
Run Code Online (Sandbox Code Playgroud)

我读过这个页面:什么是NullPointerException,我该如何解决?(所以不要报告重复请)

而我理解的是我得到错误,因为我的ArrayList没有任何元素.但是,我尝试在创建它之后立即添加一个,如下所示:

ArrayList<Fiducial> activList  ;
activList.add(new Fiducial(3, 4.0, 5.0 ));
Run Code Online (Sandbox Code Playgroud)

但我得到错误:"意外的令牌:("在行:

activList.add(new Fiducial(3, 4.0, 5.0 ));
Run Code Online (Sandbox Code Playgroud)

我不明白,我认为添加一个元素会阻止它为空但我仍然会收到错误.我该怎么修改呢?

谢谢你的帮助

Cli*_*int 8

你永远不会实际ArrayList使用它new.没有分配内存ArrayList.

修复如下:

ArrayList<Fiducial> activList = new ArrayList<Fiducial>();
Run Code Online (Sandbox Code Playgroud)

来自文档:

实例化:new关键字是创建对象的Java运算符.

初始化:new运算符后面是对构造函数的调用,该构造函数初始化新对象.

创建对象文档

只有原始类型(int,double等)才会声明变量,因为你为它分配了内存.对象需要new关键字具有与之关联的内存.