【问题标题】:Why am I getting a NullPointerException on this boolean array?为什么我在这个布尔数组上得到 NullPointerException?
【发布时间】:2015-02-07 05:24:26
【问题描述】:

在我的类的构造函数中,我使用boolean[] list = new boolean[n] 初始化一个布尔数组,其中n 是构造函数的唯一参数,并且我将list 的每个索引分配给trueArrays.fill(list, true)。编辑:list 首先使用private boolean[] list 在构造函数外部创建

然后在一个方法中我这样做:

//n still refers to the parameter in the constructor
for(int i = 2; i < n; i++){
    if(list[i]){
        for(int j = i; j < n; j*=i){
            list[j] = false;
        }
    }
}

并且if(list[i]) 抛出 NullPointerException,即使我使用 Arrays.fill(list, true) 初始化了所有 list。我最初有一个循环,将 list 中的所有内容单独设置为 true,并且给出了相同的错误,所以现在我很难过。

编辑:这是完整的构造函数。

public Seive(int n){

        //create an array of booleans of length n
        list = new boolean[n];
        this.n = n;

        //set all booleans in the array to true
        Arrays.fill(list, true);

        //set 0 and 1 to false so that the algorithm can ignore them 
        //and they won't be put into the list of primes
        list[0] = false;
        list[1] = false;

}

我遗漏了一件我刚刚意识到很重要的事情:我使用private boolean[] list 在构造函数之外创建list,因此引发异常的方法应该能够访问数组。在发布这段代码之前,我还做了 Eran 建议的更改。

【问题讨论】:

  • 显示构造函数(我怀疑你在屏蔽list)。
  • 显示你所有的构造函数,以及 this n 如何仍然引用构造函数中的参数

标签: java arrays nullpointerexception boolean


【解决方案1】:

由于您在构造函数中有这个 - boolean[] list = new boolean[n]; -,所以这个数组在构造函数中被声明和初始化。该方法访问另一个未初始化的同名数组(可能是您在类中声明的成员)。

将构造函数中的初始化更改为:

list = new boolean[n];

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多