簡體   English   中英

空指針異常 - 將項添加到ArrayList

[英]Null Pointer Exception - Adding item to ArrayList

我對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.

牆類:

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! :)

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

編輯:

確實,聲明這樣一個字段的傳統方法是將接口用作類型,如下所示:

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

你永遠不會初始化ArrayList; 你已經在內存中保留了一個位置,但是在你初始化之前它的值是null。

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

walls是一個引用,它必須指向一個對象(通常使用new創建),然后再調用它上面的任何方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM