实现说明
Integer 缓存与装箱陷阱的核心是类 AutoboxIdentity和函数 main。
使用要点
- 跑完文件,输出里会留下标记——
127 == 127:、128 == 128:、128 equals 128:。
常见问题
运行「Integer 缓存与装箱陷阱」会打印什么?
不用做任何设置,直接把文件跑完——输出里的 127 == 127:、128 == 128:、128 equals 128: 标签标明各步骤。
核心语句
Integer smallA = 127;
Integer smallB = 127;
int primitive = 128;
代码示例
public class AutoboxIdentity {
public static void main(String[] args) {
// -128..127 的装箱命中 IntegerCache:同一个对象
Integer smallA = 127;
Integer smallB = 127;
System.out.println("127 == 127: " + (smallA == smallB));
// 超出缓存:每次装箱都是新对象,== 比的是引用
Integer bigA = 128;
Integer bigB = 128;
System.out.println("128 == 128: " + (bigA == bigB));
System.out.println("128 equals 128: " + bigA.equals(bigB));
// 与 int 比较触发拆箱:== 回到数值语义
int primitive = 128;
System.out.println("unboxed ==: " + (bigA == primitive));
// valueOf 显式走同一缓存
System.out.println("valueOf(127) == 127-box: " + (Integer.valueOf(127) == smallA));
}
}