检查数组元素是否为空以避免Java中的NullPointerEx

检查数组元素是否为空以避免Java中的NullPointerEx

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

问题描述

我有一个部分 nfill 的对象数组,当我遍历它们时,我试图在我用它做其他事情之前检查所选对象是否为 null.然而,即使检查它是否为 null 的行为似乎也是通过 NullPointerException.array.length 也将包含所有 null 元素.你如何检查数组中的 null 元素?例如在下面的代码中会为我抛出一个 NPE.

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");
            }
        }
    }
}

并得到预期的输出:

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

您是否可能尝试检查 someArray[index] 的长度?

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

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

08-06 03:32