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

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

提问人:user37857 提问时间:1/9/2009 最后编辑:Lahiru Ashanuser37857 更新时间:3/8/2018 访问量:211422

问:

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

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

评论

1赞 d0k 1/9/2009
你的代码没有给我一个NPR。您可能还想使用“i<someArray.length”而不是“i<=someArray.length-1”
0赞 bancer 11/9/2010
如果您检查,它会抛出 NPE。!someArray.equals(null)

答:

24赞 Richard Campbell 1/9/2009 #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]的长度?

1赞 Brett Daniel 1/9/2009 #2

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

1赞 Dave Costa 1/9/2009 #3

好吧,首先,代码不会编译。

删除 i++ 后面的额外分号后,它对我来说编译并运行良好。

6赞 OscarRyz 1/9/2009 #4

事实并非如此。

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

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>
1赞 Raymond Roestenburg 1/9/2009 #5

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

3赞 Lakshmi Prasanna 8/10/2015 #6
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循环。

0赞 nani 2/9/2017 #7
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;

}
-2赞 Michal Demjančuk 3/8/2018 #8

你可以在一行代码上完成(没有数组声明):

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

评论

0赞 Mushroomator 10/29/2023
这是 C#,而问题是关于 Java 的。