我是 Java 的新手,在检查整数数组中的空元素时遇到问题。 我正在使用 Eclipse 作为编辑器,检查 null 元素的行显示错误:
提示的线路:
if(a[i] != null) {
来自 Eclipse 的错误消息:
The operator != is undefined for the argument type(s) int, null
在 PHP 中,这没有任何问题,但在 Java 中,似乎我必须将数组类型从整数更改为 Object 以使行不提示(如下所示)
Object[] a = new Object[3];
所以我的问题是如果我仍然想声明为整数数组并且仍然想检查空值, 它的语法是什么?
代码:
public void test() {
int[] a = new int[3];
for(int i=0; i<a.length; i++) {
if(a[i] != null) { //this line complains...
System.out.println('null!');
}
}
}
最佳答案
在 Java 中,int
是原始类型,不能为 null
。然而,对象存储为引用,因此如果您声明一个对象引用但不创建一个新
对象,该引用将为null
。
Integers
是 ints
的对象包装器,这意味着它们可以是 null
。
public void test() {
Integer[] a = new Integer[3];
for(int i=0; i<a.length; i++) {
if(a[i] != null) { //should now compile
System.out.println('null!');
}
}
}
关于java - 如果它是 Java 中的整数数组,如何检查 null 元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3033633/