Integer类中默认缓存-128~127之间的整数值

本文深入探讨了Java中Integer对象的缓存机制,解析了valueOf方法如何通过缓存提高空间和时间性能,特别是在-128到127范围内的整数。通过示例代码展示了当使用相同int值创建Integer对象时,缓存机制如何影响对象的引用相等性。

当我们给一个 Integer 对 象赋一个 int 值的时候,会调用 Integer 类的静态方法 valueOf,如果看看 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);
    }

而IntegerCache.cache[],里面就是默认的缓存值,所以,就出现了,如下结果:

        Integer t1 = 23;
        Integer t2 = 23;
        Integer t3 = 223;
        Integer t4 = 223;
        System.out.println(t1 ==t2);// true
        System.out.println(t3 ==t4);// false

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值