我对Java的处理方式有点困惑==
and equals()
到那个时刻int
, Integer
和其他类型的数字。例如:
Integer X = 9000;
int x = 9000;
Short Y = 9000;
short y = 9000;
List<Boolean> results = new ArrayList<Boolean>();
// results.add(X == Y); DOES NOT COMPILE 1)
results.add(Y == 9000); // 2)
results.add(X == y); // 3)
results.add(X.equals(x)); // 4)
results.add(X.equals(Y)); // 5)
results.add(X.equals(y)); // 6)
System.out.println(results);
输出(也许你应该先猜测):
[true, true, true, false, false]
- That
X == Y
不编译是可以预料的,因为它们是不同的对象。
- 我有点惊讶
Y == 9
is true
,假定 9 默认为int
,并考虑到 1) 甚至没有编译。请注意,您不能将int
进入一个期望的方法Short
,但在这里它们是平等的。
- 出于与两个相同的原因,这令人惊讶,但似乎更糟。
- 并不奇怪,因为
x
自动装箱为 和Integer
.
- 这并不奇怪,因为不同类中的对象不应该
equal()
.
- What??
X == y
is true
but X.equals(y)
is false
?不应该==
总是比equals()
?
如果有人能帮助我理解这一点,我将不胜感激。 == 和 equals() 这样做的原因是什么?
Edit:我已将 9 更改为 9000,以表明此行为与 -128 到 127 之间的整数的任何异常行为方式无关。
2nd Edit: OK, if you think you understand this stuff, you should consider the following, just to make sure:
Integer X = 9000;
Integer Z = 9000;
short y = 9000;
List<Boolean> results = new ArrayList<Boolean>();
results.add(X == Z); // 1)
results.add(X == y); // 2)
results.add(X.equals(Z)); // 3)
results.add(X.equals(y)); // 4)
System.out.println(results);
outputs:
[false, true, true, false]
据我了解,原因是:
- 不同的实例,所以不同。
-
X
拆箱后,价值相同,因此相等。
- 相同的值,所以相等。
-
y
不能装箱到Integer
所以不能相等。