Java:简述1000==1000返回false,100==100返回true

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_29229567/article/details/84628651

Java:简述1000 = = 1000返回false,100 = = 100返回true

大家觉得如下代码的结果是什么呢?

public static void main(String[] args) {
   Integer a = 1000, b = 1000;
   System.out.println(a == b);

   Integer c = 100, d = 100;
   System.out.println(c == d);
}

实际的结果如下:

false
true

我们知道:
如果两个引用指向同一个对象,那么它们使用"= =“比较返回true.
如果两个引用指向不同的对象,那么即使它们具有相同的内容,它们使用”= ="比较返回false。

当我们声明类似以下内容的时候:

Integer a = 1000;

它实际在进行如下操作:

Integer i = Integer.valueOf(1000);

我们来看看Integer.valueOf()这个方法:

public static Integer valueOf(int i) {
    if (i >= IntegerCache.low && i <= IntegerCache.high)
        return IntegerCache.cache[i + (-IntegerCache.low)];
   return new Integer(i);
}

再查看Integer.java类,会发现有一个内部私有类,IntegerCache.java,它缓存-128和127之间的所有Integer对象。

public final class Integer extends Number implements Comparable {
    ......
     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之间,那么将返回缓存中的对象,所以是同一个对象。
    如果是这个范围之外的值,则会创建新的对象。

通常情况下,小整数比大整数使用得更频繁,因此使用相同的底层对象来减少潜在的内存占用。

猜你喜欢

转载自blog.csdn.net/qq_29229567/article/details/84628651
今日推荐