不,==在整数,长等之间将检查引用相等 – 即
Integer x = ...;
Integer y = ...;
System.out.println(x == y);
这将检查x和y是否指向相同的对象而不是等于对象。
所以
Integer x = new Integer(10);
Integer y = new Integer(10);
System.out.println(x == y);
保证打印为假。实现“小”自动装箱值可能会导致棘手的结果:
Integer x = 10;
Integer y = 10;
System.out.println(x == y);
这将打印为真,由于拳击规则(JLS section 5.1.7)。它仍然使用引用相等,但引用真的是相等的。
我个人会使用:
if (x.intValue() == y.intValue())
要么
if (x.equals(y))
后者效率稍低一些 – 对于Integer.equals(Integer)没有重载,所以它必须执行执行时类型检查,而第一个使用事实,我们已经知道两个对象都是整数。
幸运的是,compareTo知道类型,所以:
if (x.compareTo(y) < 0)
应该仍然有效。当然,这是微优化领域,你应该使用你找到最清晰的代码 – 确保它是正确的:)
正如你所说,对于包装器类型(整数,长等)和数字类型(int,long等)之间的任何比较,包装器类型值被取消装箱,并且测试被应用于所涉及的原始值。
这是二进制数字促销(JLS section 5.6.2)的一部分。查看每个运算符的文档以查看它是否应用。例如,从==和!=的文档(JLS 15.21.1):
If the operands of an equality
operator are both of numeric type, or
one is of numeric type and the other
is convertible (§5.1.8) to numeric
type, binary numeric promotion is
performed on the operands (§5.6.2).
和对于和> =(JLS 15.20.1)
The type of each of the operands of a
numerical comparison operator must be
a type that is convertible (§5.1.8) to
a primitive numeric type, or a
compile-time error occurs. Binary
numeric promotion is performed on the
operands (§5.6.2). If the promoted
type of the operands is int or long,
then signed integer comparison is
performed; if this promoted type is
float or double, then floating-point
comparison is performed.
请注意,如果这两种类型都不是数字类型,则不会将其视为这种情况的一部分。