Integer的相等比較

好比下面例子:java

            Integer a1 = Integer.valueOf(60);  //直接比較
            Integer b1 = 60;    
            System.out.println("1:="+(a1 == b1));     
              
      
            Integer a2 = 60;    
            Integer b2 = 60;    
            System.out.println("2:="+(a2 == b2));    
              
      
            Integer a3 = new Integer(60);    //自動裝箱
            Integer b3 = 60;    
            System.out.println("3:="+(a3 == b3));    
              
            Integer a4 = 129;    
            Integer b4 = 129;    
            System.out.println("4:="+(a4 == b4));   
            
            Integer a5 = new Integer(60);    //自動裝箱
            Integer b5 = new Integer(60);    
            System.out.println("5:="+(a5 == b5)); 數組

你們能夠猜一下輸出是什麼,也能夠在ide裏面運行一下,那麼會發現,第四個爲何輸出falseide

1:=true
2:=true
3:=false
4:=false
5:=falseorm

關於第五個,第三個輸出應該沒有什麼異議,由於使用了new的,在==比較的時候只是針對對象引用地址做比較,因此爲false,那麼第2個爲何和第四個輸出不一樣,這就涉及到jdk遠嗎裏面,對象

jdk對-128 --127之間的數值設立了緩衝區,回去緩衝區讀取數據,可是對於這個範圍以外的數據沒有緩衝區,因此第二個和第四個輸出結果不同,下面是jdk對於Integer源碼這段的實現:get

  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 HighPropValue =
                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;it

            cache = new Integer[(high - low) + 1];
            int j = low;
            for(int k = 0; k < cache.length; k++)
                cache[k] = new Integer(j++);io

            // range [-128, 127] must be interned (JLS7 5.1.7)
            assert IntegerCache.high >= 127;
        }編譯

        private IntegerCache() {}
    }

你們能夠看到h值能夠經過配置去指定,可是通常好像沒人指定,因此此處的high通常就是127,low就是-128,cache是一個Integer類型的數組,在new的時候大小通常就是256,而後裏面的值就是-128-127(j++就是先把前面的事情幹了再去加一操做)

然而再看Integer.valueOf(60);這段在jdk中:

public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }

他會首先去檢查緩衝區中的值,有的話就從緩衝區中取出,沒有的話從新new一個,並且Integer i= 60;會被編譯成Integer i = Integer.value(60);因此以第一個會輸出true。

同理第四個在輸出的時候129已經再也不緩衝區中了,就會從新再堆中new一個新對象,因此用等號去比較的時候只是比較的兩個Integer對象的引用,因此會輸出false。

相關文章
相關標籤/搜索