java的Integer中也會有緩存 java的自動拆箱會發生NPE

在上篇《java的自動拆箱會發生NPE》博客中接收了java中的Integer中的自動拆箱產生的NPE,其實對於所有的包裝類來說都是一樣的,都會產生這樣的問題,大家需要舉一反三,做學問學知識要懂得反思總結。

一、前情回顧

先回顧下上次的知識點,

自動拆箱 實際調用的是intValue()方法

自動裝箱 實際調用的是valueOf(int i)方法

其他的包裝類,小夥伴們自己總結

二、Integer的本地緩存

好了話不多說,書接上回,開始這次的分享,上次說到在自動裝箱的時候還大有玄機,這個玄機就是本地緩存。這個玄機在自動裝箱的方法中,如下

/**
     * 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) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }

先看下其方法說明吧,用我大學英語六級的水平給大家翻譯下,獻醜了大家莫怪,

返回一個代表指定int的Integer對象,如果一個新的Integer實例不是必需的,這個方法通常使用構造方法來生成,另一方面,這個方法通常爲了節省空間和實際會緩存一些經常使用的值

這個方法會緩存[-128~127]間的值,也可能會緩存這個範圍以外的值

翻譯的太差勁了,大體意思是如果參數在[-128,127]間則會從緩存中取,如果不在則直接生成Integer的實例。還有很重要的一點最大值可以配置。

看方法的邏輯也是這樣的,看下Integer初始化緩存的代碼,在Integer中有靜態內部類IntegerCache,代碼

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循環,生成緩存
            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中存在[-128,127]範圍內的的256個緩存Integer實例。

三、驗證本地緩存

上面說到,在Integer中存在緩存,重要的一點是在調用valueOf()方法的時候纔會校驗緩存,valueOf方法共有以下幾個

重要聲明,在使用構造方法的時候是沒有緩存的,看構造方法

 /**
     * Constructs a newly allocated {@code Integer} object that
     * represents the specified {@code int} value.
     *
     * @param   value   the value to be represented by the
     *                  {@code Integer} object.
     */
    public Integer(int value) {
        this.value = value;
    }

那麼在驗證的時候就不能使用構造方法的方式,需要使用自動裝箱的方式。

1、構造方法沒有緩存

public class TestIntegerConstruct {
    public static void main(String[] args) {
        Integer i1=new Integer(1);
        Integer i2=new Integer(1);
        System.out.println(i1==i2);

    }
}

打印結果爲,

false

Process finished with exit code 0

打印出來爲false,說明i1和i2爲兩個不同的對象。

2、valueOf()方法纔有的緩存

使用valueOf構造兩個Integer對象,

public class TestValueOf {
    public static void main(String[] args) {
        Integer i1=1;
        Integer i2=1;
        System.out.println(i1==i2);
    }
}

打印結果爲,

true

Process finished with exit code 0

說明i1和i2爲同一個實例,這裏使用的是==來判斷,對引用對象來說判斷的不正是其地址。

 

多說一點,這裏兩個引用類型的比較,大家不要像我這裏似的,使用“==”,請使用equals方法,使用“==”比較的是內存地址,在大部分情況下,內存地址肯定不相等,而使用equals方法就說不準了,equals方法比較的是什麼?

3、Integer的equals方法

看下Integer的equals方法比較的是什麼東西

public boolean equals(Object obj) {
        if (obj instanceof Integer) {
            return value == ((Integer)obj).intValue();
        }
        return false;
    }

看到沒,搜先判斷的是類型,然後調用其intValue方法,也就是拆箱,比較的是Integer中value的值,也就是數值的比較。

四、總結

本文,分享了Integer中的本地緩存,需要明白以下幾個問題,

1、什麼時候會用到本地緩存?--調用valueOf方法的時候

2、本地緩存的大小;--默認爲[-128,127],最大值可設置

3、equals方法比較的是什麼;--比較的是值得大小,非內存地址

 

往期推薦

java的自動拆箱會發生NPE

源碼中的設計模式--單例模式

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