1. 程式人生 > 實用技巧 >JAVA基礎- 為啥 Integer 中100=100 為true 而200=200則為false

JAVA基礎- 為啥 Integer 中100=100 為true 而200=200則為false

話不多說,直接看題

 @Test
     public void inspectInteger(){

         Integer i1 = 100;
         Integer i2 = 100;

         Integer i3 = 200;
         Integer i4 = 200;

         Integer i5 = 300;
         Integer i6 = 300;

         Integer i7 = 1000;
         Integer i8 = 1000;

         System.out.println(i1==i2); //true
         System.out.println(i3==i4); //false
         System.out.println(i5==i6); //false
         System.out.println(i7==i8); //false

     }

預設理解 :

JAVA 用物件建立,預設是引用記憶體地址,所以 == 判斷地址,正常不應該為:true

通過多次對比,我們發現只有值為100時候,不符合我們的邏輯,其它的都為:false

所以:到底是我們對==理解有誤,還是值為:100的時候搞鬼了。通常我們有疑惑就得去驗證。

直接看Integer 原始碼 ,

 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;
//從這裡可以看到,能夠Vm配置引數,設定最大值
       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); //對比,外部配置值,是否超出了int範圍
} 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++);
       // 範圍 [-128,127] 必須被拘禁 // range [-128, 127] must be interned (JLS7 5.1.7) assert IntegerCache.high >= 127; } private IntegerCache() {} }

  原始碼中有個內部類 IntegerCache 從名字上就可以判斷: 整型快取

可以看到使用了一個Integer[] 陣列方式進行快取 ,而且可以使用VM外部設定: 最大屬性值

  預設範圍 -128 ~ 127 所以 : 也就是說 在這個範圍內的 == 都可以為true

把整數常量int 賦值 給 整數物件 Integer 型別,實際上呼叫了Integer.valueOf方法,通過原始碼也可以看到

public static Integer valueOf(int i) {
    if (i >= IntegerCache.low && i <= IntegerCache.high)     //在範圍內的,直接從cache獲取
        return IntegerCache.cache[i + (-IntegerCache.low)];
    return new Integer(i);  //否則,則new
}

  

好處:

為什麼要這麼設計,一個東西誕生不會無緣無故,目前看到說法都是 -128 ~127 比較常用,這樣可以提高效率