在Integer class,有private static class IntegerCache.
这门课有什么用?
使用时如何受益Integer?
高速缓存-128和127之间的值以供重用.这是flyweight模式的一个示例,它通过重用不可变对象来最小化内存使用.
除了优化之外,此行为是JLS的一部分,因此可以依赖以下内容:
Integer a = 1;
Integer b = 1;
Integer c = 999;
Integer d = 999;
System.out.println(a == b); // true
System.out.println(c == d); // false
Run Code Online (Sandbox Code Playgroud)
IntegerCache 缓存 -128 到 +127 之间的值以优化自动装箱。
您可以将上限设置为大于127使用-XX:AutoBoxCacheMax=NEWVALUE或-Djava.lang.Integer.IntegerCache.high=NEWVALUE