我有两个应该比较的变量:
Double a = 1D;
Double b = 2D;
if (a > b) {
System.out.print("Ok");
}
在这种情况下,java将使用自动装箱或比较两个对象的引用?
最佳答案
来自section 15.20.1 of the JLS :
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.
Section 5.6.2开头为:
When an operator applies binary numeric promotion to a pair of operands, each of which must denote a value that is convertible to a numeric type, the following rules apply, in order, using widening conversion (§5.1.2) to convert operands as necessary:
- If any of the operands is of a reference type, unboxing conversion (§5.1.8) is performed.
所以是的,拆箱已执行。 >
对于引用本身没有任何意义。
更有趣的是 ==
情况,其中两个选项都都是可能的 - 在这种情况下,如果其中一个操作数是原语并且另一个可以通过数字提升进行转换,然后就会发生这种情况...但是如果两者都是引用类型,则执行引用比较。例如:
Double d1 = new Double(1.0);
Double d2 = new Double(1.0);
System.out.println(d1 == d2); // Prints false due to reference comparison
关于java - Java 如何比较两个包装变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8545835/