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

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

问题描述

我有对象的部分nfilled阵列,而当我遍历它们我试图检查所选对象是否为空我做其他的东西与它之前。但是,检查是否是空的,即使该行为似乎通过一个NullPointerException异常。 array.length将包括所有空元素。你如何去检查数组中的null元素?例如在下面的code会抛出NPE我。

 对象[] [] =的someArray新的对象[5] [];
的for(int i = 0; I< = someArray.length-1;我++)
{
    如果(的someArray [I]!= NULL){//做一些事情
    }
}


解决方案

您有更多的事情比你说。我跑到下面的扩展测试从例如:

 公共类的测试{    公共静态无效的主要(字串[] args){
        对象[] [] =的someArray新的对象[5] [];
        的someArray [0] =新的对象[10];
        的someArray [1] =无效;
        的someArray [2] =新对象[1];
        的someArray [3] = NULL;
        的someArray [4] =新对象[5];        的for(int i = 0; I< = someArray.length-1;我++){
            如果(的someArray [I]!= NULL){
                的System.out.println(不为空);
            }其他{
                的System.out.println(空);
            }
        }
    }
}

和得到预期输出:

  $ / cygdrive / C /程序\\文件/的Java / jdk1.6.0_03 /斌/ java命令。测试
不为空
空值
不为空
空值
不为空

您可能想检查的的someArray长度[索引]

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]?

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

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