Integer是不可变对象

参考源代码,value是final类型的,不可变。

private final int value;

public static Integer valueOf(int i) {
        assert IntegerCache.high >= 127;
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            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) {
                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);
            }
            high = h;

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

        private IntegerCache() {}
    }

看看如下代码的运行结果:

public static void main(String[] args) {

        Integer a = 10;
        Integer b = 10;
        System.out.println("a == b  " + (a == b));
        System.out.println("a.equals(b)  " + (a.equals(b)));
    

        a = new Integer(10);
        b = new Integer(10);
        System.out.println("a == b  " + (a == b));
        System.out.println("a.equals(b)  " + (a.equals(b)));
    

        a = 166;
        b = 166;
        System.out.println("a == b  " + (a == b));
        System.out.println("a.equals(b)  " + (a.equals(b)));        
    }
结果如下:

      a==b  true         a.equals(b) true                 解释: -128~127之间的数值,从cache中提取

      a==b  false         a.equals(b) true                解释: new Integer(10)分配新内存

      a==b  false         a.equals(b) true                解释:超过127的数据,重新分配内存

 

不可变对象,不要使用同步锁,如下代码不可靠,应该使用Object obj:

                     Integer aa = 100;

                     synchronized(aa){

                     }

                   如果aa的值发生变化,如aa=102,而aa指向新的对象,原来锁定的代码块失去同步的意义了。

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

XiaoGong1688

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值