java新手,需要一些指针
我试图在一个类中创建一个数组列表,然后返回它,并在一个单独的主类中迭代它的值。然而,当我使用get方法返回数组中的特定值时,它会产生一个空指针异常。我做错了什么?
import java.util.*
public class ReadFile
{
private ArrayList<Integer> height;
public ReadFile()
{
ArrayList<Integer> height = new ArrayList<Integer>();
for(int x = 0; x <= 3; x++)
{
height.add(x);
}
}
public ArrayList<Integer> getHeights()
{
return height;
}
}
主要类别
import java.util.*
public class Jumper
{
private ReadFile readFile;
public Jumper()
{
readFile = new ReadFile();
}
public static void main(String[] arg)
{
Jumper game = new Jumper();
System.out.println(game.readFile.getHeights().get(1));
}
}
您正在声明一个名为height
:的字段
private ArrayList<Integer> height;
然后你要定义一个局部变量,也称为height
:
public ReadFile()
{
ArrayList<Integer> height = new ArrayList<Integer>();
在构造函数中使用height
所做的一切都是在局部变量上完成的,而在字段上什么都不做。
这一行是的问题
ArrayList<Integer> height = new ArrayList<Integer>();
您不需要为height
成员字段赋值,而是创建一个仅存在于构造函数中的新height
变量。
您应该改为执行height = new ArrayList<Integer>();
,类似于执行readFile
。
p.S:具有与成员字段同名的局部变量被称为"局部变量";可变阴影";。根据您使用的IDE,它可能会警告您,因为这不是一个常见的错误。
请在ReadFile
的构造函数中将此行ArrayList<Integer> height = new ArrayList<Integer>();
更改为height = new ArrayList<Integer>();
。结果是两个height
引用都不同。
在这个代码
public ReadFile() {
ArrayList<Integer> height = new ArrayList<Integer>();
for(int x = 0; x <= 3; x++) {
height.add(x);
}
}
height
是构造函数ReadFile()
的本地,因此只有它被初始化,而private ArrayList<Integer> height;
保持为null,这就是导致异常的原因。