【问题标题】:How to check if array element is null to avoid NullPointerException in Java如何检查数组元素是否为空以避免Java中的NullPointerException
【发布时间】:2010-09-30 08:09:07
【问题描述】:

我有一个部分填充的对象数组,当我遍历它们时,我尝试检查所选对象是否为null,然后再对其进行其他操作。然而,即使是检查它是否是null 的行为似乎也是通过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
    } 
}

【问题讨论】:

  • 你的代码没有给我 NPR。您可能还想使用“i
  • 如果你检查!someArray.equals(null),它会抛出NPE。

标签: java arrays exception-handling nullpointerexception


【解决方案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

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

【讨论】:

    【解决方案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>
    

    【讨论】:

      【解决方案3】:
      String labels[] = { "MH", null, "AP", "KL", "CH", "MP", "GJ", "OR" }; 
      
      if(Arrays.toString(labels).indexOf("null") > -1)  {
          System.out.println("Array Element Must not be null");
                           (or)
          throw new Exception("Array Element Must not be null");
      }        
      ------------------------------------------------------------------------------------------         
      
      For two Dimensional array
      
      String labels2[][] = {{ "MH", null, "AP", "KL", "CH", "MP", "GJ", "OR" },{ "MH", "FG", "AP", "KL", "CH", "MP", "GJ", "OR" };    
      
      if(Arrays.deepToString(labels2).indexOf("null") > -1)  {
          System.out.println("Array Element Must not be null");
                       (or)
          throw new Exception("Array Element Must not be null");
      }    
      ------------------------------------------------------------------------------------------
      
      same for Object Array    
      
      String ObjectArray[][] = {{ "MH", null, "AP", "KL", "CH", "MP", "GJ", "OR" },{ "MH", "FG", "AP", "KL", "CH", "MP", "GJ", "OR" };    
      
      if(Arrays.deepToString(ObjectArray).indexOf("null") > -1)  {
          System.out.println("Array Element Must not be null");
                    (or)
          throw new Exception("Array Element Must not be null");
        }
      

      如果你想找到一个特定的空元素,你应该像上面所说的那样使用for循环。

      【讨论】:

        【解决方案4】:

        给定的代码对我有用。请注意, someArray[i] 始终为 null,因为您尚未初始化数组的第二维。

        【讨论】:

          【解决方案5】:

          嗯,首先这些代码无法编译。

          删除 i++ 后多余的分号后,它可以编译并运行良好。

          【讨论】:

            【解决方案6】:

            示例代码不会抛出 NPE。 (i++后面也不应该有';')

            【讨论】:

              【解决方案7】:

              判断代码是否正在编译我会说创建一个由 6 个 5 加 2 个值组成的数组并打印它们,你将得到这两个值,而其他值为空。问题是虽然大小为 5 但数组中有 2 个对象。如何查找数组中有多少对象

              【讨论】:

                【解决方案8】:
                public static void main(String s[])
                {
                    int firstArray[] = {2, 14, 6, 82, 22};
                    int secondArray[] = {3, 16, 12, 14, 48, 96};
                    int number = getCommonMinimumNumber(firstArray, secondArray);
                    System.out.println("The number is " + number);
                
                }
                public static int getCommonMinimumNumber(int firstSeries[], int secondSeries[])
                {
                    Integer result =0;
                    if ( firstSeries.length !=0 && secondSeries.length !=0 )
                    {
                        series(firstSeries);
                        series(secondSeries);
                        one : for (int i = 0 ; i < firstSeries.length; i++)
                        {
                            for (int j = 0; j < secondSeries.length; j++)
                                if ( firstSeries[i] ==secondSeries[j])
                                {
                                    result =firstSeries[i];
                                    break one;
                                }
                                else
                                    result = -999;
                        }
                    }
                    else if ( firstSeries == Null || secondSeries == null)
                        result =-999;
                
                    else
                        result = -999;
                
                    return result;
                }
                
                public static int[] series(int number[])
                {
                
                    int temp;
                    boolean fixed = false;
                    while(fixed == false)
                    {
                        fixed = true;
                        for ( int i =0 ; i < number.length-1; i++)
                        {
                            if ( number[i] > number[i+1])
                            {
                                temp = number[i+1];
                                number[i+1] = number[i];
                                number[i] = temp;
                                fixed = false;
                            }
                        }
                    }
                    /*for ( int i =0 ;i< number.length;i++)
                    System.out.print(number[i]+",");*/
                    return number;
                
                }
                

                【讨论】:

                  【解决方案9】:

                  您可以在一行代码中完成(无需声明数组):

                  object[] someArray = new object[] 
                  {
                      "aaaa",
                      3,
                      null
                  };
                  bool containsSomeNull = someArray.Any(x => x == null);
                  

                  【讨论】:

                    猜你喜欢
                    • 1970-01-01
                    • 2013-07-20
                    • 2019-05-14
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    • 2015-01-13
                    • 1970-01-01
                    • 2016-12-01
                    相关资源
                    最近更新 更多