Boxing and Unboxing

本文通过一个简单的Java程序示例,探讨了整数装箱过程中利用缓存机制的特点,特别是对于小范围整数值的处理方式。文章揭示了当整数值位于-128到127之间时,其装箱后的Integer对象会复用已有的实例,而超出这个范围则不会共享同一对象。

请预测下面程序运行的结果:

 

 

正确结果是:

True

False

 

你“目测”的结果对吗?

 

至于原因情况下面的这段E文解释:

A further subtlety is that boxed values may be cached. Caching is required when boxing an int or short value between -128 and 127, a char value between '/u0000' and '/u007f', a byte, or a boolean; and caching is permitted when boxing other values. This is because 6 is smaller than 128, so boxing the value 6 always returns exactly the same object.

 

Even for small values, for which == will compare values of type Integer correctly, we recommend against its use. It is clearer and cleaner to use equals rather than == to compare values of reference type, such as Integer or String.

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值