我有一个部分填充的对象数组,当我遍历它们时,我试图检查所选对象是否null
在我用它做其他东西之前.然而,甚至检查它是否null
似乎是通过a NullPointerException
.array.length
将包括所有null
元素.你如何检查null
数组中的元素?例如,在下面的代码中将为我抛出一个NPE.
Object[][] someArray = new Object[5][]; for (int i=0; i<=someArray.length-1; i++) { if (someArray[i]!=null) { //do something } }
Richard Camp.. 22
你说的比你说的更多.我从你的例子中运行了以下扩展测试:
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]的长度?
你说的比你说的更多.我从你的例子中运行了以下扩展测试:
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]的长度?
它不是.
见下文.您发布的程序按预期运行.
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>