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

我有一个部分填充的对象数组,当我循环访问它们时,我试图在对它执行其他操作之前检查所选对象是否在。但是,即使是检查它是否似乎是通过. 也将包括所有元素。如何检查数组中的元素?例如,在下面的代码中,将为我抛出一个NPE。nullnullNullPointerExceptionarray.lengthnullnull

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

答案 1

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

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

您是否可能尝试检查某些数组[索引]的长度?


答案 2

事实并非如此。

见下文。您发布的程序按预期运行。

C:\oreyes\samples\java\arrays>type ArrayNullTest.java
public class ArrayNullTest {
    public static void main( String [] args ) {
        Object[][] someArray = new Object[5][];
            for (int i=0; i<=someArray.length-1; i++) {
                 if (someArray[i]!=null ) {
                     System.out.println("It wasn't null");
                 } else {
                     System.out.printf("Element at %d was null \n", i );
                 }
             }
     }
}


C:\oreyes\samples\java\arrays>javac ArrayNullTest.java

C:\oreyes\samples\java\arrays>java ArrayNullTest
Element at 0 was null
Element at 1 was null
Element at 2 was null
Element at 3 was null
Element at 4 was null

C:\oreyes\samples\java\arrays>