Java 5以后为优化内存占用对整数类型提供了自动装箱缓存机制,在一定范围内的整数自动装箱时生成的对象是指向缓存地址的。
注意自动装箱是通过Integer a = 10;这种方式来声明的,实际上会调用Integer.valueOf();在这个方法中,使用了缓存数组。如果是通过new Integer则每次都会新建对象。
Integer.valueOf();
/**
* Returns a {@code Integer} instance for the specified integer value.
*
* If it is not necessary to get a new {@code Integer} instance, it is
* recommended to use this method instead of the constructor, since it
* maintains a cache of instances which may result in better performance.
*
* @param i
* the integer value to store in the instance.
* @return a {@code Integer} instance containing {@code i}.
* @since 1.5
*/
public static Integer valueOf(int i) {
return i >= 128 || i < -128 ? new Integer(i) : SMALL_VALUES[i + 128];
}
/**
* A cache of instances used by {@link Integer#valueOf(int)} and auto-boxing
*/
private static final Integer[] SMALL_VALUES = new Integer[256];
static {
for (int i = -128; i < 128; i++) {
SMALL_VALUES[i + 128] = new Integer(i);
}
}
测试代码:
public class Main {
public static void main(String[] args) {
//Java整数类型的类包装类的缓存机制
//Integer 自动装箱缓存范围 -128-127,可以通过 JVM 的启动参数 -XX:AutoBoxCacheMax=size 修改最大范围
Integer i1 = 127, i2 = 127;
System.out.println("i1==i2 " + (i1 == i2));
Integer i3 = 128, i4 = 128;
System.out.println("i4==i4 " + (i3 == i4));
// Character 自动装箱缓存范围 0-127
Character c1 = 127, c2 = 127;
System.out.println("c1==c2 " + (c1 == c2));
Character c3 = 128, c4 = 128;
System.out.println("c3==c4 " + (c3 == c4));
// Byte,Short,Long 有固定范围: -128 到 127
Long l1 = 127L, l2 = 127L;
System.out.println("l1==l2 " + (l1 == l2));
Long l3 = 128L, l4 = 128L;
System.out.println("l3==l4 " + (l3 == l4));
}
}
运行结果:
参考资料:
http://www.tuicool.com/articles/AJFzEra