java 拆箱_java 自动拆箱 自动装箱

自动装箱的定义就是  基本数据类型赋值给包装类型,  拆箱则相反。

Integer integer = 122; // 自动装箱

int num = integer; //自动拆箱

wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==

想看一下源码是怎么完成自动装箱和拆箱的。 发现第一行代码自动装箱走的方法是 valueOf ,  看图

655d8df813370825a20a5886336e2e94.png

这一段逻辑判断是, 如果传过来的值在Integer对象的缓存范围内,  就直接返回缓存好了的值, 否则另外新建一个Integer实例。

小结:Integer缓存了一个装有255个数值的Integer数组, 在内部静态类IntegerCache的常量Integer[] cache中, 如果要装箱的值在缓存中就直接用传过来的值和IntegerCache常量low取得cache中与传过来的值对应的的下标

先来看一下Integer的缓存, 以下是Integer 的部分源码

1 /**

2 * Cache to support the object identity semantics of autoboxing for values between3 * -128 and 127 (inclusive) as required by JLS.4 *5 * The cache is initialized on first usage. The size of the cache6 * may be controlled by the {@code-XX:AutoBoxCacheMax=} option.7 * During VM initialization, java.lang.Integer.IntegerCache.high property8 * may be set and saved in the private system properties in the9 * sun.misc.VM class.10 */

11

12 private static classIntegerCache {13 static final int low = -128;14 static final inthigh;15 static finalInteger cache[];16

17 static{18 //high value may be configured by property

19 int h = 127;20 String integerCacheHighPropValue =

21 sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");22 if (integerCacheHighPropValue != null) {23 try{24 int i =parseInt(integerCacheHighPropValue);25 i = Math.max(i, 127);26 //Maximum array size is Integer.MAX_VALUE

27 h = Math.min(i, Integer.MAX_VALUE - (-low) -1);28 } catch( NumberFormatException nfe) {29 //If the property cannot be parsed into an int, ignore it.

30 }31 }32 high =h;33

34 cache = new Integer[(high - low) + 1]; //如果不+1,k就<=

35 int j =low;36 for(int k = 0; k < cache.length; k++)37 cache[k] = new Integer(j++);38

39 //range [-128, 127] must be interned (JLS7 5.1.7)

40 assert IntegerCache.high >= 127;41 }42

43 privateIntegerCache() {}44 }

wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==

源码中解释, 缓存是用来支持自动装箱的对象标识语义 , 它的值介于-128 (low)到127(high)之间, 且是在初次使用的时候被初始化掉

也就是说在使用Integer的时候就已经缓存好了一段 [-128,-127......254,255] 这样的 Integer数组.   那么之前的自动装箱的valueOf的方法就可以豁然开朗了。

接下来看自动拆箱调用的方法intValue

19eb11466b24f54519d292f6637a96c0.png

直接返回整型

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值