Integer == 和 equals 的区别

本文深入探讨了Java中Integer对象的缓存机制,详细解释了当整数值位于-128至127范围内时,Integer对象如何通过IntegerCache进行复用,以及此机制在提高空间和时间性能方面的作用。同时,文章强调了在这个区间外创建Integer对象时的内存分配行为,并推荐在比较Integer对象时使用equals方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

当装包对象在IntegerCache.low到Integer.high之间时,结果直接从 IntegerCache中获取,否则直接创造一个实例。源码如下:

/**
     * 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);
    }

所有的相同类型的包装类对象之间 值的比较 ,应该全部使用 equals 方法比较。
说明:
对于 Integer var = ? 在-128 至 127 范围内的赋值, Integer 对象是在IntegerCache . cache 产生, 会复用已有对象, 这个区间内的 Integer 值可以直接使用 ==进行判断, 但是这个区间之外的所有数据, 都会在堆上产生, 并不会复用已有对象, 这是一个大坑,
推荐使用 equals 方法进行判断。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值