[英]Why am I getting a NullPointerException on this boolean array?
In my class' constructor, I initialize a boolean array with boolean[] list = new boolean[n]
where n
is the only parameter for the constructor, and I assign every index of list
to true
with Arrays.fill(list, true)
. 在我的类的构造函数中,我使用
boolean[] list = new boolean[n]
初始化一个布尔数组,其中n
是构造函数的唯一参数,并使用Arrays.fill(list, true)
将list
每个索引分配为true
。 EDIT: list
is first created outside the constructor with private boolean[] list
:编辑
list
首先与构造函数外创建private boolean[] list
Then in a method I do this: 然后在一种方法中,我这样做:
//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;
}
}
}
And if(list[i])
throws the NullPointerException, even though I initialized all of list
with the Arrays.fill(list, true)
. 而且即使我使用
Arrays.fill(list, true)
初始化了所有list
, if(list[i])
也会引发NullPointerException。 I originally had a loop that individually set everything in list
to true, and that gave the same error, so now I'm stumped. 我最初有一个循环,单独将
list
所有内容都设置为true,并且给出了相同的错误,所以现在我很困惑。
EDIT: Here's the full constructor. 编辑:这是完整的构造函数。
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;
}
I left one thing out that I just realized was important: I create list
outside of the constructor with private boolean[] list
, so the method that the exception is thrown in should be able to access the array. 我离开一件事的是,我才意识到是重要的:我创建
list
与构造以外private boolean[] list
,这样会引发异常的方法应该能够访问阵列。 I also made the change that Eran suggested before posting this block of code. 在发布此代码块之前,我还进行了Eran建议的更改。
Since you have this - boolean[] list = new boolean[n];
既然有了
boolean[] list = new boolean[n];
- in your constructor, this array is declared and initialized locally in the constructor. -在构造函数中,此数组在构造函数中本地声明和初始化。 The method accesses a different array with the same name (probably the member you declared in your class) that is not initialized.
该方法访问未初始化的具有相同名称的另一个数组(可能是您在类中声明的成员)。
Change the initialization in your constructor to : 将构造函数中的初始化更改为:
list = new boolean[n];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.