【问题标题】:Returning Integer Array List from another class returns null pointer exceptions when getting specific value从另一个类返回整数数组列表在获取特定值时返回空指针异常
【发布时间】:2021-11-28 02:49:39
【问题描述】:

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

【问题讨论】:

    标签: java arraylist nullpointerexception


    【解决方案1】:

    您正在声明一个名为 height 的字段:

    private ArrayList<Integer> height;
    

    然后你要声明一个局部变量也叫height:

    public ReadFile()
    {
        ArrayList<Integer> height = new ArrayList<Integer>();
    

    你在构造函数中对height所做的一切都是在局部变量上完成的,而不是在字段上完成的。

    【讨论】:

      【解决方案2】:

      请在ReadFile 的构造函数中将这一行ArrayList&lt;Integer&gt; height = new ArrayList&lt;Integer&gt;(); 更改为height = new ArrayList&lt;Integer&gt;();。发生的情况是 height 引用不同。

      在这段代码中

      public ReadFile() {
      
          ArrayList<Integer> height = new ArrayList<Integer>();
      
          for(int x = 0; x <= 3; x++) {
              height.add(x);
          }
      }
      

      height 是构造函数 ReadFile() 的本地变量,因此只有它被初始化,private ArrayList&lt;Integer&gt; height; 保持为空,这就是导致异常的原因。

      【讨论】:

        【解决方案3】:

        这行是问题

        ArrayList&lt;Integer&gt; height = new ArrayList&lt;Integer&gt;();

        您无需为height 成员字段分配值,而是创建一个仅存在于构造函数内部的新height 变量。

        您应该改为使用height = new ArrayList&lt;Integer&gt;();,类似于使用readFile

        P.S:有一个与成员字段同名的局部变量称为“变量阴影”。根据您使用的 IDE,它可能会警告您,因为这不是一个不常见的错误。

        【讨论】:

        • 谢谢 Erik,效果很好:)
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-05-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多