java - Java 如何比较两个包装变量?

标签 java autoboxing

我有两个应该比较的变量:

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/

相关文章:

java - 如何在Java中的HashMap中获取某些特定范围的键的值?

java - Java 中使用泛型函数进行整数/int 自动装箱查询

java - 使用 Apache Shiro 保护 Rest 服务资源

Java App Engine 获取自动生成的键值

java - 子类抛出 UnsupportedOperationException 与忽略输入参数

java - 自动装箱/自动拆箱不适用于有界类型参数

java - Java 中自动装箱时的 NPE

java - TCP 连接 - 服务器仅在关闭套接字后发送消息

java - 是否保证 new Integer(i) == i 在 Java 中?

java - 为什么 java 不将 int[] 自动装箱到 Integer[]