默认情况下,Java对原语进行二进制数字提升,但对对象不做同样的事情。这是一个快速测试来演示:
public static void main(String... args) {
if(100 == 100L) System.out.println("first trial happened");
if(Integer.valueOf(100).equals(Long.valueOf(100))) {
System.out.println("second trial was true");
} else {
System.out.println("second trial was false");
}
if(100D == 100L) System.out.println("third trial, fun with doubles");
}
输出:
first trial happened
second trial was false
third trial, fun with doubles
这显然是正确的行为 - anInteger
不是. 但是,是否存在以与返回 true 相同的方式返回 true 的子类的“值等于”?或者?换句话说,是否有一种方法(不是)可以对对象执行相当于二进制数字提升行为的方法?Long
Number
100 == 100L
100d == 100L
Object.equals