数字提升和平等?
可能的重复:
包装类和 == 运算符
我有一个来自朋友的谜题。就是这样:
public class Test{
public static void main(String[] args){
Integer i = 1000; //10
Integer y = 1000; //10
System.out.println(i == y);
}
}
结果将为 FALSE。这是正确的。但当将 i,y 值替换为 10 时,结果为 TRUE。
据我所知,当运算符 == 应用于引用变量时,它将测试它们是否引用同一个对象。我不知道为什么会出现这样的结果,但我猜测是数字提升的问题。我真的需要帮助。 感谢每一位。
Possible Duplicate:
Wrapper class and == operator
I have a puzzle from my friend. Here is it:
public class Test{
public static void main(String[] args){
Integer i = 1000; //10
Integer y = 1000; //10
System.out.println(i == y);
}
}
The result will be FALSE. That's right. But when replacing the i,y value by 10, the result is TRUE.
From what I've read, when the operator == is applied to reference variables, it will test whether they refer to the same object. I don't know why the results like that, but I guess the problem in numeric promotion. I really need a help.
Thank every one.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
没有任何提升,因为 10 和 1000 作为数字文字,属于 int 类型。
但是有一个针对小整数对象的值池,类似于字符串池,因为大多数值都很小,或者更频繁地使用小值。但为了限制池的大小,它只涵盖 -128 到 127 之间的一些值。
根据经验:对于对象,始终将它们与 equals 进行比较,仅将基本类型与 == 进行比较。
There is nothing promoted, since 10 and 1000, as numeric literal, are of type int.
But there is a value pool for small Integer-Objects, similar to the stringpool, since most values are small, or small values are used more often. But to limit the size of the pool, it only covers some values between -128 and 127.
As a rule of thumb: For Objects, always compare them with equals, only elementary types with ==.