为什么这段代码在这里给我一个空异常错误?

Why is this code giving me a null exception error here?

为什么会抛出空异常指针错误,我该如何解决这个问题,谢谢。如果你能解释一下该怎么做。我试图将 txt 文件中的每一行存储到一个数组列表中,该数组列表进入一个更大的单独行数组列表。

    public static ArrayList<ArrayList<String>> addAfter(String file1)throws IOException{
    Scanner scanner = new Scanner(new File(file1));
    ArrayList<ArrayList<String>> arr = new ArrayList<ArrayList<String>>(); 
    ArrayList<String> a = null;
    boolean check = false;
    while(scanner.hasNextLine())
    {
        String str = scanner.nextLine();
        String[] stringArr = str.split(" +");
        for(int i=0; i<stringArr.length; i++){
            a.add(stringArr[i]); //null exception being thrown here
        }
        stringArr = null;
        arr.add(a);
        a.clear();
    }
    return arr;
    }

因为这个:

ArrayList<String> a = null;

ArrayList 已声明但未初始化。因此,当您在 for 循环中访问 ArrayList 时,您基本上是在访问引用 null 的变量 a。

改为:

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

此外,您的代码还有一个问题: 您希望创建一个 ArrayList 的 ArrayList,您在循环中传递相同对象的引用(而不是在循环中创建新的 ArrayList)并在 for 循环结束时清除它。这会导致相同的 ArrayList 被添加到 ArrayList<ArrayList<>> 的所有索引中。 您必须为要插入 arrayList 的每个新行执行 new ArrayList<String>()

修改您的代码以执行相同的操作:

public static ArrayList<ArrayList<String>> addAfter(String file1)throws IOException{
Scanner scanner = new Scanner(new File(file1));
ArrayList<ArrayList<String>> arr = new ArrayList<ArrayList<String>>(); 
ArrayList<String> a = null;
boolean check = false;
while(scanner.hasNextLine())
{
    a = new ArrayList<String>(); // add this
    String str = scanner.nextLine();
    String[] stringArr = str.split(" +");
    for(int i=0; i<stringArr.length; i++){
        a.add(stringArr[i]); //null exception being thrown here
    }
    stringArr = null;
    arr.add(a);
    //a.clear(); -- remove this line
}
return arr;

在 Java 中,您传递的是引用而不是值(对于对象)。

您没有初始化 "a" ArrayList 对象。

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

而不是

ArrayList<String> a = null;

在Java中,对象变量不包含对象本身,而是对对象在内存中真正所在位置的引用。当您获得 NullPointerException 时,这意味着 Java 无法访问对象,因为对象变量为 null 而不是对对象的引用。

使用这个。

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