Integer 类型比较大小

== 比较 Integer 大小

Integer n1 = 127;
Integer n2 = 127;
System.out.println(n1 == n2);       // true
System.out.println(n1.equals(n2));  // true
Integer n1 = 128;
Integer n2 = 128;
System.out.println(n1 == n2);       // false
System.out.println(n1.equals(n2));  // true

首先Integer n1 = 127; 这种赋值方式,是会进行装箱操作的;
下面我们看一下源码

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

本质是因为 Integer 内部维护了一个IntegerCache,
-128 到 127 是byte的取值范围,如果在这个取值范围内,自动装箱就不会创建对象,而是从常量池中获取,如果超过了byte的取值返回就会再新创建对象;

猜你喜欢

转载自www.cnblogs.com/Godfunc/p/9195533.html