Java 自动装箱 (Autoboxing Q+A)

1.

Q. How does autoboxing handle the following code fragment?
译: 自动装箱怎样处理下面的代码片段 ?

Integer a = null;
int b = a;

A. It results in a run-time error. Primitive type can store every value of their corresponding wrapper type except null.
译: 导致一个运行时异常。原始数据类型可以存储其相应包装类型的每个值,null 除外。

2.

Q. Why does the first group of statements print true, but the second false?
译: 为什么第一组语句打印为 true, 第二组打印为 false ?

Integer a1 = 100;
Integer a2 = 100;
System.out.println(a1 == a2);   // true

Integer b1 = new Integer(100);
Integer b2 = new Integer(100);
System.out.println(b1 == b2);   // false

Integer c1 = 150;
Integer c2 = 150;
System.out.println(c1 == c2);   // false

A. The second prints false because b1 and b2 are references to different Integer objects. The first and third code fragments rely on autoboxing. Surprisingly the first prints true because values between -128 and 127 appear to refer to the same immutable Integer objects (Java's implementation of valueOf() retrieves a cached values if the integer is between -128 and 127), while Java constructs new objects for each integer outside this range.

译: 第二个打印 false 是因为 b1 和 b2 是两个不同 Integer 对象的引用。第一个和第三个代码片段依赖于自动装箱。令人惊讶的是第一个打印为 true,因为介于 -128 和 127 之间的值似乎引用了相同的不可变整数对象 ( 如果该整数介于 -128 和 127 之间,valueOf() 的实现将检索缓存的值 ) 而 Java 会构造新对象用于此范围之外的每个整数。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Lua 5.1 参考手册 by Roberto Ierusalimschy, Luiz Henrique de F...
    苏黎九歌阅读 13,919评论 0 38
  • 如果时光可以倒流,我还是会选择认识你,虽然会伤痕累累,但是心中的温暖记忆是谁都无法给与的。谢谢你来过我的世界。
    Gardenia_3094阅读 131评论 0 0
  • 坚持原创分享第187天 加班回到家,看到屋子一片狼藉,厨房还泡着昨天的碗,洗衣篮里有一大堆脏衣服,前两天洗好...
    我是一只没有脚的鸟阅读 291评论 0 0
  • 不离开北京也许不会想那么多,每天都活在一个相对安逸平静的环境中,对生活反倒没了一丝想法。 不想说北京的...
    努力吧小子阅读 249评论 1 1
  • 以下都是个人的一点拙见,纯属个人感觉,最终解释权归本人所有,不喜勿喷。 我认为现在入手一款新机...
    Mr雷_5788阅读 602评论 6 6