为什么Integer用==比较时127相等而128不相等?

发布时间 2023-03-26 08:16:42作者: 百里浅暮

首先回顾一下自动装箱。对于下面这行代码:

Integer a = 1;

变量a为Integer类型,而1为int类型,且Integer和int之间并无继承关系,按照Java的一般处理方法,这行代码应该报错。

但因为自动装箱机制的存在,在为Integer类型的变量赋int类型值时,Java会自动将int类型转换为Integer类型,即:

Integer a = Integer.valueOf(1);

valueOf()方法返回一个Integer类型值,并将其赋值给变量a。这就是int的自动装箱。

自动装箱并不一定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);
}

其注释里就直接说明了-128到127之间的值都是直接从缓存中取出的。看看是怎么实现的:如果int型参数i在IntegerCache.low和IntegerCache.high范围内,则直接由IntegerCache返回;否则new一个新的对象返回。似乎IntegerCache.low就是-128,IntegerCache.high就是127了。 

看看IntegerCache的源码:在其static块中就一次性生成了-128到127直接的Integer类型变量存储在cache[]中,对于-128到127之间的int类型,返回的都是同一个Integer类型对象。

整个工作过程就是:Integer.class在装载(Java虚拟机启动)时,其内部类型IntegerCache的static块即开始执行,实例化并暂存数值在-128到127之间的Integer类型对象。当自动装箱int型值在-128到127之间时,即直接返回IntegerCache中暂存的Integer类型对象。

为什么Java这么设计?我想是出于效率考虑,因为自动装箱经常遇到,尤其是小数值的自动装箱;而如果每次自动装箱都触发new,在堆中分配内存,就显得太慢了;所以不如预先将那些常用的值提前生成好,自动装箱时直接拿出来返回。哪些值是常用的?就是-128到127了。

不仅int,Java中的另外7中基本类型都可以自动装箱和自动拆箱,其中也有用到缓存。见下表:

解决方法

既然我们的目的是比较数值是否相等,而非判断是否为同一对象;而自动装箱又不能保证同一数值的Integer一定是同一对象或一定不是同一对象,那么就不要用==,直接用equals()好了。实际上,Integer重写了equals()方法,直接比较对象的数值是否相等。