【发布时间】:2015-02-07 05:24:26
【问题描述】:
在我的类的构造函数中,我使用boolean[] list = new boolean[n] 初始化一个布尔数组,其中n 是构造函数的唯一参数,并且我将list 的每个索引分配给true 和Arrays.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