Integer 用 == 比较时 127 相等 128 不相等

  • 写代码验证到 128 开始不相等
for (int i = 0; i < 150; i++) {
  Integer a = i;
  Integer b = i;
  System.out.println(i + " " + (a == b));
}

输出结果:
126 true
127 true
.........
128 false
129 false

可以看到:从 128 开始 a 和 b 就不再相等

  • 自动装箱
    • 解析这行代码 Integer a = 1
    • 变量 a 为 Integer 类型,而 1 为 int 类型,且 Integer 和 int 之间并无继承关系,按照 Java 的一般处理方法,这行代码应该报错
    • 因为自动装箱机制的存在,在为 Integer 类型的变量赋 int 类型值时,Java 会自动将 int 类型转换为 Integer 类型
    • 赋值变量的时候会执行这行代码:Integer a = Integer.valueOf(1);
    • valueOf() 方法返回一个 Integer 类型值,并将其赋值给变量 a,这就是 int 的自动装箱
    • 每次循环时,Integer a = i 和 Integer b = i 都会触发自动装箱,而自动装箱会将 int 转换 Integer 类型值并返回
    • Java 中两个 new 出来的对象因为时不同的实例,无论如何 == 都会返回 fasle,例如:new Integer(1) == new Integer(1);
    • 那么例子 中Integer a = i 和 Integer b = i 自动装箱产生的变量 a 和 b 就不应该时同一个对象了,那么 == 的结果应该时 false
    • 128 以上为 false 容易理解,但为何 (-128)0 到 127 时返回 true 了呢?== 返回 true 的唯一情况是比较的两个对象为同一个对象,那不妨把例子中 a 和 b 的内存地址都打印出来看看
for(int i=0;i<150;i++){
  Integer a=i;
  Integer b=i;
  System.out.println(a+" "+b+" "+System.identityHashCode(a)+" "+System.identityHashCode(b));
}

// 可以看到从 128 开始,两个对象的 identityHashCode() 就不相等了
126 126 759156157 759156157
127 127 1635546341 1635546341
............................
128 128 1698156408 1740035246
129 129 884457408 913190639

  • 源码层面分析
    • 推测:"从 0 到 127 不同时候自动装箱得到的是同一个对象 " 就只能有一种解释:自动装箱并不一定 new 出新的对象
    • 自动装箱涉及到的方法是 Integer.valueOf(),其源码如下:
/**
     * Returns an {@code Integer} instance representing the specified
     * {@code int} value.  If a new {@code Integer} instance is not
     * required, this method should generally be used in preference to
     * the constructor {@link #Integer(int)}, as this method is likely
     * to yield significantly better space and time performance by
     * caching frequently requested values.
     *
     * This method will always cache values in the range -128 to 127,
     * inclusive, and may cache other values outside of this range.
     *
     * @param  i an {@code int} value.
     * @return an {@code Integer} instance representing {@code i}.
     * @since  1.5
     */
    public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }
    
注释里就直接说明了-128127 之间的值都是直接从缓存中取出的,看看是怎么实现的:
如果 int 型参数 i 在 IntegerCache.low 和 IntegerCache.high 范围内,则直接由
IntegerCache 返回,否则 new 一个新的对象返回
IntegerCache.low 就是 -128IntegerCache.high 就是 127


  • IntegerCache 源码分析
    • 在 static 块中就一次性生成 -128 到 127 直接的 Integer 类型变量存储在 cache[] 中,对于 -128 到 127 之间的 int 类型,返回的都是同一个 Integer 类型对象
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];
            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() {}
    }

  • 总结
    • Integer.class 在装载 ( Java 虚拟机启动 ) 时,其内部类型 IntegerCache 的 static 块即开始执行,实例化并暂存数值在 -128 到 127 之间的 Integer 类型对象。
    • 当自动装箱 int 型值在 -128 到 127 之间时,直接返回 IntegerCache 中暂存的 Integer 类型对象
    • 为什么Java这么设计?
      • 出于效率考虑,因为自动装箱经常遇到,尤其是小数值的自动装箱
      • 每次自动装箱都触发 new,在堆中分配内存,就显得太慢了
      • 预先将那些常用的值提前生成好,自动装箱时直接拿出来返回
      • 常用值的范围就是 -128 到 127

  • Java 其他基本数据类型的缓存
基本类型装箱类型取值范围是否缓存缓存范围
byteByte-128 ~ 127-128 ~ 127
shortShort-2^15 ~ (2^15 - 1)-128 ~ 127
intInteger-2^31 ~ (2^31 - 1)-128 ~ 127
longLong-2^63 ~ (2^63 - 1)-128~127
floatFloat
doubleDouble
booleanBooleantrue, falsetrue, false
charCharacter\u0000 ~ \uffff\u0000 ~ \u007f
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

tytler

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

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

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

打赏作者

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

抵扣说明:

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

余额充值