本文介绍了数组中的空指针异常初始化为null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是下面的代码.我必须出于某种目的使数组为null,然后将数组组件初始化为1时,它显示了null指针异常.该如何处理?
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;
}
推荐答案
您需要先创建一个数组对象并将其分配给该数组变量,然后再尝试使用该变量.否则,您将创建NullPointerException/NPE的定义:尝试使用(取消引用)引用null的引用变量.
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;
}
}
这篇关于数组中的空指针异常初始化为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!