问题
This is the following code. I have to make the array null for a purpose, then when I initialize the array components to 1, it shows null pointer exception. How to handle this?
public static void main(String[] args) {
double[] a;
a=null;
if(a==null)
for(int i=0;i<12;i++)
a[i]=1;
}
回答1:
You need to create an array object and assign it to the array variable before trying to use the variable. Otherwise you are creating the very definition of a NullPointerException/NPE: trying to use (dereference) a reference variable that refers to null.
// constant to avoid "magic" numbers
private static final int MAX_A = 12;
// elsewhere in code
if (a == null) {
a = new double[MAX_A]; // you need this!
for (int i = 0; i < a.length; i++) {
a[i] = 1.0;
}
}
回答2:
a[i]=1
// That's the problem.
You are trying to assign a value, without actually allocating memory (aka, not initializing). Indirectly you are trying to invoke a operation on NULL object which obviously results in Null Pointer Exception
.
So
if(a == null){
a = new double[12];
//other for loop logic
}
will solve the problem. 12 is the size of the array (The number of double value it can hold/store).
回答3:
You have to create the array before initialization -
double[] a;
a=null;
if(a==null){
a = new double[12];
for (int i = 0; i < a.length; i++) {
a[i] = 1.0;
}
}
Since double
array a
is null
when you are trying to access the array element like this -
a[i]=0;
It produces NullPointerException
.
回答4:
At the first place why don't you make it NULL while declaring the variable double[] a = null;
The reason why you are getting NullPointer is because you are trying to access it when it is NULL a[i]=1;
. This is as good as String name = null; name.toString();
You are doing some operation on an NULL value so getting NullPointer.
Just initialize it and then try to access it and you will not get NullPointer. This is like you should first allocate some memory and then try to access the memory location, when no memory is allocated, you will get NullPointer which tells you that there is no memory allocated yet. Hope this helps.
来源:https://stackoverflow.com/questions/30605043/null-pointer-exception-in-array-initialized-to-null