Integer用==進行值比較,什麼時候相等,什麼時候不等?
阿新 • • 發佈:2018-11-09
package mytest; public class TestInteger { public static void main(String args[]) { Integer a =127; Integer b =127; System.out.println(a==b); a=128; b=128; System.out.println(a==b); a=-127; b=-127; System.out.println(a==b); a=-128; b=-128; System.out.println(a==b); a=-129; b=-129; System.out.println(a==b); } }
true
false
true
true
false
結果說明 在值域為 [-128,127]之間,用==符號來比較Integer的值,是相等的。為啥會有這樣的結果呢?因為Integer內部特別處理了這之間的數。
/** * 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的靜態內部類,在Integer類裝入記憶體中時,會執行其內部類中靜態程式碼塊進行其初始化工作,做的主要工作就是把 [-128,127]之間的數包裝成Integer類並把其對應的引用存入到cache陣列中,這樣在方法區中開闢空間存放這些靜態Integer變數,同時靜態cache陣列也存放在這裡,供執行緒享用,這也稱靜態快取。我們知道在Java的物件是引用的,所以當用Integer 宣告初始化變數時,會先判斷所賦值的大小是否在-128到127之間,若在,則利用靜態快取中的空間並且返回對應cache陣列中對應引用,存放到執行棧中,而不再重新開闢記憶體。
如此,便導致了上面Integer比較用==比較結果為true的情況發生。