Integer類中默認緩存-128~127之間的整數值

當我們給一個 Integer 對 象賦一個 int 值的時候,會調用 Integer 類的靜態方法 valueOf,如果看看 valueOf 的源代碼就知道發生了什麼。

 /**
     * 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);
    }

而IntegerCache.cache[],裏面就是默認的緩存值,所以,就出現了,如下結果:

        Integer t1 = 23;
        Integer t2 = 23;
        Integer t3 = 223;
        Integer t4 = 223;
        System.out.println(t1 ==t2);// true
        System.out.println(t3 ==t4);// false

 

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