一道面試題關於Integer的緩存範圍(-128~127)所引起的一系列問題記錄


某天無意中看見一道關於Integer的筆試題,問下面的輸出結果是多少:

package test;  
  
public class Test {  
  
    public static void main(String[] args) {  
        Integer i1 = 127;  
        Integer i2 = 127;  
        System.err.println(i1 == i2);  
          
        i1 = 128;  
        i2 = 128;  
        System.err.println(i1 == i2);  
    }  
} 
說實話,剛開始看到這題目自己並不確定答案,“==”對於引用類型比較的是對象地址是否相同,雖然java有自動拆箱和裝箱,但這題一看就知道並不像自己想得那麼簡單,於是將代碼粘貼到MyEclipse中運行,其輸出結果:

看到這運行結果,自己怎麼也想不通,爲什麼等於127的時候爲true,128就變成false了呢?於是自己各種百度、谷歌,其中有一個解釋是這樣的:

JVM會自動維護八種基本類型的常量池,int常量池中初始化-128~127的範圍,所以當爲Integer i=127時,在自動裝箱過程中是取自常量池中的數值,而當Integer i=128時,128不在常量池範圍內,所以在自動裝箱過程中需new 128,所以地址不一樣。

於是自己就有了很多疑問:

1.如果是兩個new 出來的Integer對象,但值在-128~127這個範圍內並相等,再通過“==”去比較會怎麼樣呢?

測試代碼如下:

package com.beauxie.javase;

public class Test2 {
    
    public static void main(String[] args) {
        Integer i1 = 6;
        Integer i2 = 6;
        System.out.println((i1==i2));//true
        
        
        Integer i3 = new Integer(6);
        Integer i4 = new Integer(6);
        
        System.out.println((6==i3));
        System.out.println((128==i3));
        System.out.println((i4==128));
        
        System.out.println((i3==i4)+" "+i3.hashCode()+" "+i4.hashCode());
        
     }

   }

}
在這裏順便打印出兩個new出來的對象的hash值,運行結果:

以上結果說明:

a.當數值範圍爲-128~127時:如果兩個new出來Integer對象,即使值相同,通過“==”比較結果爲false,但兩個對象直接賦值,則通過“==”比較結果爲“true,這一點與String非常相似。

b.當數值不在-128~127時,無論通過哪種方式,即使兩個對象的值相等,通過“==”比較,其結果爲false;

c.當一個Integer對象直接與一個int基本數據類型通過“==”比較,其結果與第一點相同;

d.Integer對象的hash值爲數值本身;


查看Integer源代碼:
  /**
     * Returns a hash code for this {@code Integer}.
     *
     * @return  a hash code value for this object, equal to the
     *          primitive {@code int} value represented by this
     *          {@code Integer} object.
     */
    public int hashCode() {
        return value;
    }

Integer重寫了hashCode方法,返回值是value,即Integer對象 的數值。

2.第二個問題,爲什麼Integer對象的範圍是-128~127?

查看Integer類源碼,發現裏面有一個私有的靜態內部類IntegerCache,而如果直接將一個基本數據類型的值賦給Integer對象,則會發生自動裝箱,其原理就是通過調用Integer類的public static Integer valueOf(將int類型的值包裝到一個對象中 ,其部分源碼如下:

 /**
     * 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 -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) {
                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);
            }
            high = h;

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

        private IntegerCache() {}
    }
   ..................
  ...................
  ...................

      /**
     * Returns an {@code Integer} instance representing the specified
     * {@code int} value.  If a new {@code Integer} instance is not
     * required, this method should generally be used in preference to
     * the constructor {@link #Integer(int)}, as this method is likely
     * to yield significantly better space and time performance by
     * caching frequently requested values.
     *
     * This method will always cache values in the range -128 to 127,
     * inclusive, and may cache other values outside of this range.
     *
     * @param  i an {@code int} value.
     * @return an {@code Integer} instance representing {@code i}.
     * @since  1.5
     */
    public static Integer valueOf(int i) {
        assert IntegerCache.high >= 127;
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }
 

查看API文檔,對valueOf(int i)的方法描述如下:

我想通過以上的分析,應該知道原因了吧,簡要的說就是在Integer類中有一個靜態內部類IntegerCache,在IntegerCache類中有一個Integer數組,用以緩存當數值範圍爲-128~127時的Integer對象。

3.第三個問題是自己在百度有關該面試題相關知識時,無意中看見的一個問題,就是爲何byte的範圍是-128~127?

以下是網上搜來的答案:

一個字節佔8bit,由於計算機只能識別二進制,即0和1。所以規定第一位是符號位,1表示負數,0表示正數,這裏涉及到補碼,如下圖所示:

這也讓我明白了爲什麼int的數值範圍是 -2^31~2^31-1(int佔4個字節,即32bit)。


一道小小的面試題居然花費了我這麼多的時間、、、


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