自动装箱 自动拆箱 以及 Integer 的缓存机制

  1. 自动装箱和自动拆箱
    把基本类型转换成包装类型的过程叫做装箱(Integer.valueOf() )。
    反之,把包装类型转换成基本类型的过程叫做拆箱(Integer.intValue())。
		Integer num1 = 10;  // 自动装箱 Integer num1 = Integer.valueOf(10);
		int num2 = num1;     // 自动拆箱 int num2 = num1.intValue();
  1. 用 "=="比较

基本类型和包装类型进行 == 比较,这时候包装类型会自动拆箱,直接比较值,所以结果为 true。
当需要进行自动装箱时,如果数字在 -128 至 127 之间时,会直接使用缓存中的对象,而不是重新创建一个对象。

		// 1)常量池,在-128~127的范围内,被缓存在常量池中
        Integer num1 = new Integer(100);//堆
        Integer num2 = new Integer(100);//堆
        int num3 = 100;//常量池
        int num4 = 100;//常量池
        Integer num5 = 100;//常量池,
        Integer num6 = 100;//
        System.out.println(num1 == num2);//false
        System.out.println(num2 == num3);//true 自动拆箱
        System.out.println(num2 == num5);//false
        System.out.println(num3 == num4);//true
        System.out.println(num3 == num5);//true 自动拆箱
        System.out.println(num5 == num6);//true 常量池,在-128~127的范围内,被缓存在常量池中
        
		//2)堆,超出-128~127的范围,不被缓存
        num1 = new Integer(200);//堆
        num2 = new Integer(200);//堆
        num3 = 200;
        num4 = 200;
        num5 = 200;
        num6 = 200;
        System.out.println(num1 == num2);//false
        System.out.println(num2 == num3);//true 自动拆箱
        System.out.println(num2 == num5);//false
        System.out.println(num3 == num4);//true
        System.out.println(num3 == num5);//true 自动拆箱
        System.out.println(num5 == num6);//false 堆,超出-128~127的范围,不被缓存
  1. 自动装箱源码
public static Integer valueOf(int i) {
    if (i >= IntegerCache.low && i <= IntegerCache.high)
        return IntegerCache.cache[i + (-IntegerCache.low)];
    return new Integer(i);
}
  1. 关键类IntegerCache
private static class IntegerCache {
    static final int low = -128;
    static final int high;
    static final Integer cache[];

    static {
        // high value may be configured by property
        int h = 127;
        int i = parseInt(integerCacheHighPropValue);
        i = Math.max(i, 127);
        h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
        high = h;

        cache = new Integer[(high - low) + 1];
        int j = low;
        for(int k = 0; k < cache.length; k++)
            cache[k] = new Integer(j++);

        // range [-128, 127] must be interned (JLS7 5.1.7)
        assert IntegerCache.high >= 127;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值