将 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()
从内部返回 Integer 对象。IntegerCache
Java 缓存这些整数对象,因为这个整数范围在日常编程中被大量使用,从而间接节省了一些内存。
由于静态块,当类被加载到内存中时,缓存在第一次使用时被初始化。缓存的最大范围可以由-XX:AutoBoxCacheMax
JVM 选项控制。
此缓存行为仅适用于 Integer 对象,类似于我们也分别拥有ByteCache, ShortCache, LongCache, CharacterCache
的Integer.IntegerCache Byte, Short, Long, Character
。
您可以阅读我的文章Java Integer Cache - Why Integer.valueOf(127) == Integer.valueOf(127) Is True了解更多信息。