int vs Integer 比较 Java
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18445158/
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
int vs Integer comparison Java
提问by UnderDog
class datatype1
{
public static void main(String args[])
{
int i1 = 1;
Integer i2 = 1;
Integer i3 = new Integer(1);
System.out.println("i1 == i2"+(i1==i2));
System.out.println("i1 == i3"+(i1==i3));
System.out.println("i2 == i3"+(i2==i3));
}
}
Output
输出
i1 == i2true
i1 == i3true
i2 == i3false
Can someone explain why I get false when comparing i2 and i3 ?
有人可以解释为什么我在比较 i2 和 i3 时会出错吗?
采纳答案by rocketboy
i1 == i2
results in un-boxingand a regular int comparison is done. (see first point in JLS 5.6.2)
导致取消装箱并完成常规的 int 比较。(参见JLS 5.6.2 中的第一点)
i2 == i3
results in reference comparsion. Remember, i2
and i3
are two different objects. (see JLS 15.21.3)
结果参考比较。请记住,i2
和i3
是两个不同的对象。(见JLS 15.21.3)
回答by Aniket Thakur
Integer i2 = 1;
This results is autoboxing. You are converting int(primitive type) to it's corresponding wrapper.
这个结果是自动装箱。您正在将 int(primitive type) 转换为其相应的包装器。
Integer i3 = new Integer(1);
Here no need of autoboxing as you are directly creating an Integer object.
这里不需要自动装箱,因为您直接创建了一个 Integer 对象。
Now in
现在在
i1 == i2
i1 == i3
i2 and i3 are automatically unboxed and regular int comparison takes place which is why you get true.
i2 和 i3 会自动拆箱,并且会进行常规的 int 比较,这就是您得到正确结果的原因。
Now consider
现在考虑
i2 == i3
Here both i2 and i3 are Integer objects that you are comparing. Since both are different object(since you have used new operator) it will obviously give false. Note == operator checks if two references point to same object or not. Infact .equals() method if not overridden does the same thing.
这里 i2 和 i3 都是您要比较的 Integer 对象。由于两者都是不同的对象(因为您使用了 new 运算符),它显然会给出 false。注意 == 运算符检查两个引用是否指向同一个对象。事实上 .equals() 方法如果没有被覆盖会做同样的事情。
It is same as saying
和说的一样
Integer i2 = new Integer(1);
Integer i3 = new Integer(1);
System.out.println("i2 == i3 "+(i2==i3));
which will again give you false.
这将再次给你错误。