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=<size>} 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()判斷。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章