【Java基础】Integer包装类的缓冲池问题

首先看下面这个例子:

public class TestNew {
    public static void main(String args[]){
        Integer i1 = 10;
        //Integer i1 = Integer.valueOf(10);
        Integer i2 = 10;
        Integer i3 = 1000;
        Integer i4 = 1000;
        System.out.println(i1 == i2);
        System.out.println(i3 == i4);
    }
}

其中注释的地方是用来表示编译器优化后代码的样子,说明应该对于i1 = 10的赋值,由于是包装类,所以要创建一个Integer对象,这样,最后两个对象的地址比较,肯定结果都是false,但是真实的结果并不是这样。

true
false

Process finished with exit code 0

第一个比较的结果竟然是true,为了弄清楚原因,就要看Integer的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) {
        assert IntegerCache.high >= 127;
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }

从这里可以看出,对于value在-128到127之间的int值,在调用这个方法创建Integer对象时,是直接从缓冲池中返回的,如果缓冲池中有,则返回的是同一个对象。

那如果此时,对i2赋值为1,是否i1也会变为1呢?

答案是否定的,上一篇文章中的包装类的参数传递问题和这个类似,因为将1赋值给i2,这时候1被自动装箱为Integer对象,并让i2指向这个新对象,所以此时不会改变i

的值。

原文地址:https://www.cnblogs.com/gslyyq/p/4950848.html