[英]why int can't be compared to null but Integer can be compared to null
Though this has been discussed in detail in various forums including SO
and I have read most of the replies of the experts, But below is the problem is confusing me. 尽管已经在包括
SO
在内的各种论坛中对此进行了详细的讨论,并且我已阅读了专家的大部分答复,但是下面的问题使我感到困惑。
I have few integer
variables and my requirement is to check null
before executing few statements. 我有几个
integer
变量,我的要求是在执行一些语句之前检查null
。 So first I have declared as int (I don't have knowledge on int and Integer)
. 所以首先我声明为
int (I don't have knowledge on int and Integer)
。
int a,b,c;
if(a == null) {
//code here
}
But complier is not allowing me to declare like this. 但是编译器不允许我这样声明。
After searching in google, experts advised me to use Integer
instead of int
and when I changed like the code below 在google中搜索后,专家建议我使用
Integer
而不是int
并且当我像下面的代码一样更改
Integer a,b,c;
if(a == null) {
//code here
}
This is fine with the compiler as Integer
is defined as Object
in java and int
is not. 这对于编译器很好,因为
Integer
在Java中定义为Object
,而int
不是。
Now my code has become some declarations with int
and some with Integer
. 现在,我的代码已成为
int
一些声明和Integer
一些声明。
Can anyone suggest if declaring Integer
will give the same result as int
also can I change all my declarations to Integer
. 任何人都可以建议声明
Integer
的结果是否与int
相同,也可以将所有声明更改为Integer
。
Thanks for your time. 谢谢你的时间。
int a,b,c;
if (a == null) {
//code here
}
This code doesn't make sense, because primitive int
types cannot be null. 这段代码没有意义,因为原始
int
类型不能为null。 Even if you considered auto-boxing, int a
is guaranteed to have a value before being boxed. 即使您考虑了自动装箱,也可以确保
int a
在装箱前具有一个值。
Integer a,b,c;
if (a == null) {
//code here
}
This code makes sense, because Object Integer
types can be null (no value). 这段代码很有意义,因为对象
Integer
类型可以为null(无值)。
As far as the functionality, the Object vs built-in types actually do make a bit of a difference (due to their different natures). 就功能而言,对象vs内置类型实际上确实有所不同(由于它们的不同性质)。
Integer a,b,c;
if (a == b) {
// a and b refer to the same instance.
// for small integers where a and b are constructed with the same values,
// the JVM uses a factory and this will mostly work
//
// for large integers where a and b are constructed with the same values,
// you could get a == b to fail
}
while 而
int a,b,c;
if (a == b) {
// for all integers were a and b contain the same value,
// this will always work
}
int
is the primitive type, and is not a nullable value (it can't ever be null). int
是原始类型,并且不是可为空的值(永远不能为null)。 Integer
is a class object, which can be null if it has not yet been instantiated. Integer
是一个类对象,如果尚未实例化,则可以为null。 Using an Integer
vs. an int
won't really affect anything in terms of functionality, and your code would behave the same if you changed "int" to "Integer" everywhere. 使用
Integer
vs. int
不会真正影响功能,如果在各处将“ int”更改为“ Integer”,代码的行为也相同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.