添加时的java arraylist空指针异常 [英] java arraylist null pointer exception when adding

查看:77
本文介绍了添加时的java arraylist空指针异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以帮助我理解为什么在添加到数组列表时为什么会得到空指针.我试图这样做,以便在单击按钮时更改按钮上的文本,但是我的 ArrayList 似乎没有在其中添加内容?

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

推荐答案

您正在阴影 Game 构造函数中的class字段 pairs .更改

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

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

pairs = new ArrayList<String>();

,例如钻石运营商

pairs = new ArrayList<>();

这篇关于添加时的java arraylist空指针异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆