将 int 文字直接分配给 Integer 引用是自动装箱的一个示例,其中文字值到对象的转换代码由编译器处理。
所以在编译阶段编译器会将Integer a = 1000, b = 1000; 转换为Integer a = Integer.valueOf(1000), b = Integer.valueOf(1000);。
所以实际上是Integer.valueOf()方法给了我们整数对象,如果我们查看Integer.valueOf()方法的源代码,我们可以清楚地看到该方法缓存了-128到127(含)范围内的整数对象.
/**
* 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 字面量大于 -128 且小于 127,Integer.valueOf() 该方法不会创建和返回新的整数对象,而是从内部 IntegerCache 返回 Integer 对象。
Java 缓存这些整数对象,因为这个整数范围在日常编程中被大量使用,间接节省了一些内存。
当类因为静态块而加载到内存中时,缓存在第一次使用时被初始化。缓存的最大范围可以通过-XX:AutoBoxCacheMax JVM 选项来控制。
这种缓存行为仅适用于 Integer 对象,类似于 Integer.IntegerCache 我们也有ByteCache, ShortCache, LongCache, CharacterCache 分别对应Byte, Short, Long, Character。
你可以在我的文章Java Integer Cache - Why Integer.valueOf(127) == Integer.valueOf(127) Is True阅读更多。