[英]Null Pointer Exception - Adding item to ArrayList
I'm a bit new to java so please dumb down the answers as if I'm a four year old. 我对java有点新鲜,所以请愚蠢的回答,好像我已经四岁了。 =-D
= -D
I'm using slick for this code. 我正在使用光滑的代码。 If you need more code please just ask.
如果您需要更多代码,请询问。 I'm trying to post only what I see as relevant, but as I'm new to programming I may be wrong.
我只想发布我认为相关的东西,但由于我是编程新手,我可能错了。
I've tracked the origin of the problem to adding a newly created object into an arrayList. 我已经跟踪问题的根源,将新创建的对象添加到arrayList中。 Here's the code:
这是代码:
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 class: 墙类:
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;
}
}
Thanks for any help or for even looking. 感谢您的帮助或甚至寻找。
The arrayList must be initialized! 必须初始化arrayList! : )
:)
public ArrayList<Walls> walls = new ArrayList<Walls>();
Edit: 编辑:
True that the conventional way to declare such a field is to use the interface as type like so: 确实,声明这样一个字段的传统方法是将接口用作类型,如下所示:
public List<Walls> walls = new ArrayList<Walls>();
You never initialize the ArrayList; 你永远不会初始化ArrayList; you've reserved a place in memory for it, but until you initialize it its value is null.
你已经在内存中保留了一个位置,但是在你初始化之前它的值是null。
public ArrayList<Walls> walls = new ArrayList<Walls>();
walls
是一个引用,它必须指向一个对象(通常使用new
创建),然后再调用它上面的任何方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.