如何检查数组元素是否为空以避免Java中的NullPointerException
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/425439/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check if array element is null to avoid NullPointerException in Java
提问by user37857
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 nullbefore I do other stuff with it. However, even the act of checking if it is nullseem to through a NullPointerException. array.lengthwill include all nullelements as well. How do you go about checking for nullelements in an array? For example in the following code will throw an NPE for me.
我有一个部分填充的对象数组,当我遍历它们时,我尝试检查所选对象是否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
}
}
采纳答案by Richard Campbell
You have more going on than you said. I ran the following expanded test from your example:
你要做的事情比你说的要多。我从您的示例中运行了以下扩展测试:
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");
}
}
}
}
and got the expected output:
并得到了预期的输出:
$ /cygdrive/c/Program\ Files/Java/jdk1.6.0_03/bin/java -cp . test
not null
null
not null
null
not null
Are you possibly trying to check the lengths of someArray[index]?
您是否可能试图检查 someArray[index] 的长度?
回答by Brett Daniel
The given code works for me. Notice that someArray[i] is always null since you have not initialized the second dimension of the array.
给定的代码对我有用。请注意, someArray[i] 始终为 null,因为您尚未初始化数组的第二维。
回答by Dave Costa
Well, first of all that code doesn't compile.
好吧,首先该代码无法编译。
After removing the extra semicolon after i++, it compiles and runs fine for me.
在 i++ 之后删除额外的分号后,它编译并运行良好。
回答by OscarRyz
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>
回答by Raymond Roestenburg
The example code does not throw an NPE. (there also should not be a ';' behind the i++)
示例代码不会抛出 NPE。(在 i++ 后面也不应该有“;”)
回答by Raymond Roestenburg
Fighting whether the code is compiling or not I would say create a array of sixe 5 add 2 values and print them , you will get the two values and others are null. The question is although the size is 5 but there are 2 objects in the array . How to find how many objects are present in the array
无论代码是否正在编译,我会说创建一个包含 5 个值的数组添加 2 个值并打印它们,您将获得两个值,其他值为空。问题是虽然大小为 5 但数组中有 2 个对象。如何查找数组中存在多少个对象
回答by Lakshmi Prasanna
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");
}
If you want to find a particular null element, you should use for loop as above said .
如果你想找到一个特定的空元素,你应该使用上面说的 for 循环。
回答by nani
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;
}
回答by Michal Demjan?uk
You can do it on one line of code (without array declaration):
您可以在一行代码上完成(没有数组声明):
object[] someArray = new object[]
{
"aaaa",
3,
null
};
bool containsSomeNull = someArray.Any(x => x == null);

