如何检查数组元素是否为空,以避免Java中的NullPointerException异常 [英] How to check if array element is null to avoid NullPointerException in Java

查看:216
本文介绍了如何检查数组元素是否为空,以避免Java中的NullPointerException异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些部分填充的对象数组,当我重复遍历它们时,我尝试检查所选对象是否为 null ,然后再进行其他操作。然而,即使是通过 NullPointerException 来检查它是否为 null 的行为。 array.length 将包括所有 null 元素。你如何检查数组中的 null 元素?例如下面的代码将为我抛出一个NPE。

  Object [] [] someArray = new Object [5] [ ]。 (int i = 0; i< = someArray.length-1; i ++){
if(someArray [i]!= null){//做某事
}
}


解决方案

你比你说的更多。我从你的例子中运行了以下扩展测试:

  public class test {

public static void main (String [] args){
Object [] [] someArray = new Object [5] [];
someArray [0] = new Object [10];
someArray [1] = null;
someArray [2] = new Object [1];
someArray [3] = null;
someArray [4] = new Object [5]; (int i = 0; i< = someArray.length-1; i ++){
if(someArray [i]!= null){
System.out。 println(not null);
} else {
System.out.println(null);
}
}
}
}

得到预期的输出:

  $ / cygdrive / c / Program\ Files / Java / jdk1.6.0_03 / bin / java -cp。 test 
not null
null
not null
null
not null

你可能试图检查someArray [index]的长度吗?


I have a partially nfilled array of objects, and when I iterate through them I tried to check to see whether the selected object is null before I do other stuff with it. However, even the act of checking if it is null seem to through a NullPointerException. array.length will include all null elements as well. How do you go about checking for null elements in an array? For example in the following code will throw an NPE for me.

Object[][] someArray = new Object[5][];
for (int i=0; i<=someArray.length-1; i++) {
    if (someArray[i]!=null) { //do something
    } 
}

解决方案

You have more going on than you said. I ran the following expanded test from your example:

public class test {

    public static void main(String[] args) {
        Object[][] someArray = new Object[5][];
        someArray[0] = new Object[10];
        someArray[1] = null;
        someArray[2] = new Object[1];
        someArray[3] = null;
        someArray[4] = new Object[5];

        for (int i=0; i<=someArray.length-1; i++) {
            if (someArray[i] != null) {
                System.out.println("not null");
            } else {
                System.out.println("null");
            }
        }
    }
}

and got the expected output:

$ /cygdrive/c/Program\ Files/Java/jdk1.6.0_03/bin/java -cp . test
not null
null
not null
null
not null

Are you possibly trying to check the lengths of someArray[index]?

这篇关于如何检查数组元素是否为空,以避免Java中的NullPointerException异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆