0

I'm getting a NullPointerException when trying to add a new instance of a Block class to an ArrayList called blocks.

Here is the code snippet containing the line of error:

public class Level1State extends GameState {

    private Player player;
    private ArrayList<Block> blocks;

    public Level1State(GameStateManager gsm) {
        super(gsm);
        this.blocks = new ArrayList<Block>();
    }

    @Override
    public void init() {
        player = new Player(30, 30);

        blocks.add(new Block(500, 400));
    }
    ...
}

And the Block class is very simple:

public class Block extends Rectangle {
    private static final long serialVersionUID = 1L;

    public static final int blockSize = 64;

    public Block(int x, int y) {
        setBounds(x,y,blockSize,blockSize);
    }

    public void tick() {

    }

    public void draw(Graphics g) {
        g.setColor(Color.DARK_GRAY);
        g.fillRect(x - (int) GameState.xOffset, y - (int) GameState.yOffset,
                width,
                height);
    }
}

Any help is appreciated.

Bashir
  • 2,057
  • 5
  • 19
  • 44
  • 1
    and ... where is an NPE thrown? how is that code called? what does setBounds do? – Stultuske Jun 16 '20 at 11:11
  • 3
    Could it be that super calls init? Why don't you initialize the list where you declare it? – assylias Jun 16 '20 at 11:24
  • @assylias it's not likely for a constructor to call an overridable method. – Stultuske Jun 16 '20 at 11:31
  • @Stultuske It's certainly bad design, but possible. – assylias Jun 16 '20 at 12:03
  • which is why I said: not likely. the problem might also be in the setBounds method of the Block constructor. We have no idea where the problem is with the information given. – Stultuske Jun 16 '20 at 12:09
  • 1
    Let me guess: your `GameState` class calls `init()` somewhere, which is overridden by your subclass, causing the `blocks` field to be *not yet* initialized. Please post the `GameState` class. – MC Emperor Jun 16 '20 at 12:35
  • Yep that was it, super(gsm) was calling init() before the arraylist was initialised, thank you so much – Jaxon Parkinson Jun 17 '20 at 08:49

0 Answers0