Java复习——12.自动拆箱和装箱(Java)和坑点

拆箱 :

Integer.intValue() 其他方法类似 xxxValue() 返回 int

装箱:

Integer.valueOf() 其他方法类似 valueOf() 返回 Integer

Integer 源码对比

public static Integer valueOf(int i) {
    if (i >= IntegerCache.low && i <= IntegerCache.high)  //先去 InterCache.cache  中去找
        return IntegerCache.cache[i + (-IntegerCache.low)];
    return new Integer(i);
}

比较特殊的点(源码分析)

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;
        String integerCacheHighPropValue =
            sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
        if (integerCacheHighPropValue != null) {
            try {
                int i = parseInt(integerCacheHighPropValue);
                i = Math.max(i, 127);
                // Maximum array size is Integer.MAX_VALUE
                h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
            } catch( NumberFormatException nfe) {
                // If the property cannot be parsed into an int, ignore it.
            }
        }
        high = h;

        cache = new Integer[(high - low) + 1];  //把  -128,127都缓存了
        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;
    }

    private IntegerCache() {}
}

通过源码可以看到,在 Interger 的 valueOf 方法中,如果数值在 [-128, 127] 范围的时候,就会去 IntegerCache.cache 这个数组寻找有没有存在的 Integer 对象的引用,如果有,则直接返回对象的引用,如果没有(超过了范围),就新建一个 Integer 对象
IntegerCache.cache 数组 对象的 装了 [-128,127]
因此 如果Integer判断是否一样 在 [-128,127] 返回是一样 其余为 fasle

坑点一

例如:

public static void main(String[] args) {
    Integer a = 1000;
    Integer b = 1000;
    Integer c = 100;
    Integer d = 100;
    System.out.println("a == b is " + (a == b));
    System.out.println("c == d is " + (c == d));
}

输出

a == b is false
c == d is true

坑点二

  @Test
    public void go1(){
        Integer a = 1 ;
        Integer b = 2 ;
        swap(a,b);
        System.out.println("a = "+ a + ", b = " + b);
    }

    private void swap(Integer n1, Integer n2) {
        Integer temp;
        temp = n1 ;
        n1 = n2;
        n2 = temp;
    }

这个看似是交换两个变量值的代码,执行结果值却没有被交换
a,b,n1,n2,temp几个变量都是在栈内存里面,这样执行后的结果a,n2,temp指向的值是1,b,n1指向的值是2,我们获取到的值是a,b对应的值(a b 的引用没有被交换),所以仍然是1,2
这时候我们查看Integer源码,发现装箱操作的变量为value,是一个private,final类型的变量
我们可以通过反射对其进行操作

 try {
       Field field = Integer.class.getDeclaredField("value"); // 反射获取对象域
       field.setAccessible(true); // 设置私有成员变量为可操作
       int temp = n1.intValue();
       field.set(n1,n2); 
       field.set(n2,temp);
   } catch (Exception e) {
       e.printStackTrace();
   }

此时发现执行结果为a=2,b=2,也并没有交换。详细看了源码之后,发现是IntegerCache导致的

    public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }

对于[-128,127]之间的数字会在IntegerCache中寻找,没有对IntegerCache进行更新,那我们查找就是上次存放的值就是我们在前面的那个数如果不再这个范围,那交换的时候,并不会影响。那样的话,IntegerCache对应位置没有发生改变。取值为我们想要的

如果我们想要更加准确一些,避免这些情况的时候
我们可以手动进行装箱,不是自动装箱,IntegerCache的元素就不会影响到

     Field field = Integer.class.getDeclaredField("value"); // 反射获取对象域
     field.setAccessible(true); // 设置私有成员变量为可操作
     int temp = n1.intValue();
     field.set(n1,n2); 
     field.set(n2,new Integer(temp)); // 重点

参考链接:
链接1:https://blog.csdn.net/WeiJiFeng_/article/details/79975593
链接2:https://blog.csdn.net/li_wei_quan/article/details/90552910

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值