盒装原语和等价
所以今天有人问我这个问题。
Integer a = 3;
Integer b = 2;
Integer c = 5;
Integer d = a + b;
System.out.println(c == d);
这个程序会打印出什么?它返回 true。我回答说,由于我对自动(和自动取消)装箱的理解,它总是会打印出错误。我的印象是分配 Integer a = 3 将创建一个新的 Integer(3),以便 == 将评估引用而不是原始值。
谁能解释一下吗?
So I was asked this question today.
Integer a = 3;
Integer b = 2;
Integer c = 5;
Integer d = a + b;
System.out.println(c == d);
What will this program print out? It returns true. I answered it will always print out false because of how I understood auto (and auto un) boxing. I was under the impression that assigning Integer a = 3 will create a new Integer(3) so that an == will evaluate the reference rather then the primitive value.
Can anyone explain this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
缓存 -128 到 127 之间的装箱值。装箱使用
Integer.valueOf
方法,该方法使用缓存。范围之外的值不会被缓存,并且始终创建为新实例。由于您的值属于缓存范围,因此使用 == 运算符使值相等。引用Java语言规范:
http://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html#jls-5.1.7
Boxed values between -128 to 127 are cached. Boxing uses
Integer.valueOf
method, which uses the cache. Values outside the range are not cached and always created as a new instance. Since your values fall into the cached range, values are equal using == operator.Quote from Java language specification:
http://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html#jls-5.1.7
这就是实际发生的情况:
Java 在 -128 到 127 之间维护
Integer
对象的缓存。与以下内容进行比较:哪个应该打印
false
。This is what is really happening:
Java maintains a cache of
Integer
objects between -128 and 127. Compare with the following:Which should print
false
.这是因为一些(自动装箱的)整数被缓存,所以您实际上是在比较相同的引用 - 这篇文章有更详细的例子和解释。
It's because some of the (auto-boxed) Integers are cached, so you're actually comparing the same reference -- this post has more detailed examples and an explanation.
缓存也发生在自动装箱之外,请考虑这一点:
这将打印:
通常在比较对象时您希望远离
==
Caching happens outside of autoboxing too, consider this:
this will print:
Generally you want to stay away from
==
when comparing Objects