3

Could someone please help me understand why i'm getting a null pointer when adding to my array list. Im trying to make it so that it will change the text on a button when it is clicked, however my ArrayList does not seem to be adding the things into it?

public class Game {

private GUI gui;
private ArrayList<String> pairs;
boolean clicked; 

public Game() {
    gui = new GUI(this);
    clicked = false; 
    ArrayList<String> pairs = new ArrayList<String>();

}

public void addPairs() {
    pairs.add("dog"); // where i get the null pointer
    pairs.add("dog");
}

2 Answers 2

3

You are shadowing the class field pairs in your Game constructor. Change

ArrayList<String> pairs = new ArrayList<String>();

to

pairs = new ArrayList<String>();

or with the diamond operator like

pairs = new ArrayList<>();
Sign up to request clarification or add additional context in comments.

Comments

2

You should initialize the class member pairs

this.pairs = new ArrayList<>(); // this may be omitted

instead of creating a new local list

ArrayList<String> pairs = new ArrayList<String>();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.