class D {
public static void main(String args[]) {
Integer b2=128;
Integer b3=128;
System.out.println(b2==b3);
}
}
输出:
false
class D {
public static void main(String args[]) {
Integer b2=127;
Integer b3=127;
System.out.println(b2==b3);
}
}
输出:
true
注意:-128至127之间的数字为真。
当你使用Java编译数字文字并将其分配给Integer(大写I
)时,编译器将发出:
Integer b2 =Integer.valueOf(127)
当你使用自动装箱时,也会生成此行代码。
valueOf 实现了“合并”某些数字,对于小于128的值,它将返回相同的实例。
从Java 1.6源代码的第621行:
public static Integer valueOf(int i) {
if(i >= -128 && i <= IntegerCache.high)
return IntegerCache.cache[i + 128];
else
return new Integer(i);
}
high可以使用system属性将的值配置为另一个值。
-Djava.lang.Integer.IntegerCache.high = 999
如果使用该系统属性运行程序,它将输出true!
显而易见的结论是:永远不要依赖两个相同的引用,始终将它们与.equals()
方法进行比较。
因此,b2.equals(b3)
对于b2,b3的所有逻辑相等值,将输出true。
请注意,Integer
出于性能原因不存在缓存,而是为了符合JLS,第5.1.7节;必须为-128至127(含)之间的值指定对象标识。
Integer#valueOf(int)也记录此行为: