以下代码对我来说看起来很令人困惑,因为它提供了两个不同的输出。这段代码在JDK 1.7上进行了测试。
public class NotEq {
public static void main(String[] args) {
ver1();
System.out.println();
ver2();
}
public static void ver1() {
Integer a = 128;
Integer b = 128;
if (a == b) {
System.out.println("Equal Object");
}
if (a != b) {
System.out.println("Different objects");
}
if (a.equals(b)) {
System.out.println("Meaningfully equal.");
}
}
public static void ver2() {
Integer i1 = 127;
Integer i2 = 127;
if (i1 == i2) {
System.out.println("Equal Object");
}
if (i1 != i2){
System.out.println("Different objects");
}
if (i1.equals(i2)){
System.out.println("Meaningfully equal");
}
}
}
输出:
[ver1 输出]
不同的对象
具有实际相等性。[ver2 输出]
相等的对象
具有实际相等性
为什么对于值远小于Integer.MAX_VALUE的数字,== 和 != 检测会为 ver1() 和 ver2() 产生不同的结果?可以得出结论,对于大于127的数字(如代码中的 Integer 包装类),使用 == 进行检测完全是浪费时间吗?