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 比較常用,這樣可以提高效率

     

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM