Java中判断Integer类型相等的问题

Java中判断Integer类型相等的问题

Java中判断Integer类型是否相等时,使用.equals== 是有区别的

public static void main(String[] args) {
     
		Integer t1 = 127;
		Integer t2 = 127;
		Integer t3 = 128;
		Integer t4 = 128;
		System.out.println(t1 == t2);
		System.out.println(t3 == t4);
	}

控制台输出如下:

true
false

原因如下:
当用“==”进行比较时,jvm默认是比较数据在java堆的地址。int是一种基本数据类型,jvm会自动将Integer转成int数值进行比较。在Integer类中,有一个内部静态类IntegerCache ,用来支持自动拆箱和装箱,如下,数值范围[-128,127]

/**
     * Cache to support the object identity semantics of autoboxing for values between
     * -128 and 127 (inclusive) as required by JLS.
     *
     * The cache is initialized on first usage.  The size of the cache
     * may be controlled by the {@code -XX:AutoBoxCacheMax=} option.
     * During VM initialization, java.lang.Integer.IntegerCache.high property
     * may be set and saved in the private system properties in the
     * sun.misc.VM class.
     */

    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的值范围在[-128,127]之间是可以用 == 来判断的,否则就要用 .equals()或者 .intValue()判断。

你可能感兴趣的:(Java,java)