关于Java中的整数类型值比较的疑问

面试题中经常会考察一些比较基础的问题,比如下面关于同样大小的整数进行比较,结果却不同。

先看一段代码

package com.joshua317;

public class Main {

    public static void main(String[] args) {
        Integer a = 100;
        Integer b = 100;

        Integer c = 200;
        Integer d = 200;

        System.out.println(a == b);
        System.out.println(c == d);
    }
}

先思考下,结果是什么呢???


思考5秒钟......


看下结果:

 

 

 

为什么同样都是整数,得到的结果却不同呢?

或许你会说:

如果两个引用指向同一个对象,用 == 表示它们是相等的。

如果两个引用指向不同的对象,用 == 表示它们是不相等的,即使它们的内容相同

回答正确!

这就很有趣了,接下来我们探究一下为什么会这样呢?

我们断点来看下内部运行的原理

 

 

 

原来在Integer类中,执行了valueOf方法

public final class Integer extends Number implements Comparable<Integer> {

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

}
Java

然后会发现,有一个内部私有类,IntegerCache.java,它缓存了从 - 128 到 127 之间的所有的整数对象。

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() {}
    }

如果值的范围在 - 128 到 127 之间,它就从高速缓存返回实例。

所以变量a和b指向了同一个对象,在比较的时候返回的是ture。

Integer a = 100;
Integer b = 100;

而变量c和d指向了不同的对象,在比较的时候返回的是false。

Integer c = 200;
Integer d = 200;

这也说明了一开始我们说的那句话

如果两个引用指向同一个对象,用 == 表示它们是相等的。

如果两个引用指向不同的对象,用 == 表示它们是不相等的,即使它们的内容相同

或许你可能会问,为什么 - 128 到 127 之间的数据需要缓存?

那是因为在此范围内的 “小” 整数使用率比大整数要高,因此,使用相同的底层对象是有价值的,可以减少潜在的内存占用。

当然通常情况下,我们在比较两个整数值大小的时候,或者说是包装类型间的相等判断的时候,应该用equals,而不是'=='。

接下来我们看如下代码

package com.joshua317;

public class Main {

    public static void main(String[] args) {
        Integer a = 100;
        Integer b = 100;

        Integer c = 200;
        Integer d = 200;
        System.out.println(a.equals(b));
        System.out.println(c.equals(d));
    }
}

结果如下:

 

 

 

这是因为

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

完整代码示例:

package com.joshua317;

public class Main {

    /**
     * 如果两个引用指向同一个对象,用 == 表示它们是相等的。
     * 如果两个引用指向不同的对象,用 == 表示它们是不相等的,即使它们的内容相同
     *
     * 对于Integer var=?在-128至127之间的赋值,Integer对象是在IntegerCache.cache产生,会复用已有对象,这个区间内的Integer值可以直接使用==进行判断,但是这个区间之外的所有数据,都会在堆上产生,并不会复用已有对象,所有的包装类对象之间值的比较,全部使用equals方法比较。
     * 这是一个大坑,推荐使用equals方法进行判断。
     */
    public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
        Integer a = 100;
        Integer b = 100;

        Integer c = 200;
        Integer d = 200;

        System.out.println(a == b);
        System.out.println(c == d);

        System.out.println(a.equals(b));
        System.out.println(c.equals(d));
    }
}

 

posted @ 2021-10-15 18:42  joshua317  阅读(115)  评论(0编辑  收藏  举报