【问题标题】:Null Pointer Exception - Adding item to ArrayList空指针异常 - 将项目添加到 ArrayList
【发布时间】:2013-06-18 08:16:10
【问题描述】:

我对 java 有点陌生,所以请把答案当成四岁的样子。 =-D

我在这段代码中使用了 slick。如果您需要更多代码,请询问。我试图只发布我认为相关的内容,但由于我是编程新手,所以我可能错了。

我已经追踪到将新创建的对象添加到 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.

墙类:

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;
  }

       }

感谢您的任何帮助甚至寻找。

【问题讨论】:

  • 公共 ArrayList 墙壁 = new ArrayList();

标签: java arraylist nullpointerexception


【解决方案1】:

arrayList 必须初始化! :)

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

编辑:

确实,声明此类字段的常规方法是使用接口作为类型,如下所示:

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

【讨论】:

  • 甚至更好,也许 - public List&lt;Walls&gt; walls = new ArrayList&lt;Walls&gt;();
  • 我真是太傻了。我什至花了 30 多分钟在我的 Wall 课程中寻找和改变价值观……哈哈
  • 这样的事情只需要理解一次,别担心,我相信你很快就会掌握的。
【解决方案2】:

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

【讨论】:

    【解决方案3】:
    public ArrayList<Walls> walls = new ArrayList<Walls>();
    

    walls 是一个引用,在调用任何方法之前必须指向一个对象(通常使用new 创建)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-02-16
      • 2023-03-05
      • 1970-01-01
      • 1970-01-01
      • 2014-07-19
      • 2016-01-22
      • 1970-01-01
      相关资源
      最近更新 更多