空指针异常 - 将项添加到ArrayList

时间:2013-06-18 08:16:11

标签: java arraylist nullpointerexception

我对java有点新意,所以请把答案愚蠢,好像我已经四岁了。 = -D

我正在使用光滑的代码。如果您需要更多代码,请询问。我只想发布我认为相关的东西,但由于我是编程新手,我可能错了。

我已经跟踪了将新创建的对象添加到arrayList中的问题的根源。 这是代码:

public ArrayList<Walls> walls;
Walls w1 = new Walls(new RPoint(100,100), brickwall, brickwall, 100);
walls.add(w1); //this is where the error will occur at.

Walls课程:

package main;

import org.newdawn.slick.Image;
import org.newdawn.slick.geom.Rectangle;

public class Walls {

private RPoint p;
private Image i;
private Image i2;
private int durability;
//private Rectangle r = new Rectangle (1,1,1,1);

public Walls(RPoint a, Image b, Image c, int d){
    this.p=a;
    this.i=b;
    this.i2=c;
    this.durability=d;
//  Rectangle r = new Rectangle(Math.round(a.getX()), Math.round(a.getY()), Math.round(b.getWidth()), Math.round(b.getHeight()));

}

  public Image getImage()
  {
     return this.i;
  }

//  public Rectangle getRect()
//  {
//     return this.r;
//  }

  public Image getSecondaryImage()
  {
     return this.i2;
  }

  public int getLife()
  {
     return this.durability;
  }

  public RPoint getPoint()
  {
     return this.p;
  }

       }

感谢您提供任何帮助或甚至寻找。

3 个答案:

答案 0 :(得分:4)

必须初始化arrayList! :)

public ArrayList<Walls> walls = new ArrayList<Walls>();

修改

确实,声明这样一个字段的传统方法是将接口用作类似的类型:

public List<Walls> walls = new ArrayList<Walls>();

答案 1 :(得分:0)

你永远不会初始化ArrayList;你已经在内存中保留了一个位置,但是在你初始化之前它的值是null。

答案 2 :(得分:0)

public ArrayList<Walls> walls = new ArrayList<Walls>();

walls是一个引用,它必须指向一个对象(通常使用new创建),然后才能在其上调用任何方法。