How to check if array element is null to avoid NullPointerException in Java

后端 未结 9 1076
情深已故
情深已故 2020-12-16 13:08

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

9条回答
  •  北荒
    北荒 (楼主)
    2020-12-16 13:33

    It does not.

    See below. The program you posted runs as supposed.

    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>
    

提交回复
热议问题