java - 使用 == 运算符比较包装类和基元时类型转换背后的逻辑是什么?

标签 java wrapper autoboxing type-promotion

我读到,当需要多个操作来执行隐式转换时,编译器拒绝使用自动装箱/拆箱(int -> double -> DoubleInteger -> int -> double )。还是比较困惑

Integer i = 2;
Double d = 2.0;
System.out.println(i == d); // COMPILE TIME ERROR

// fix

System.out.println( (double) i == d); // OK: true

我的理解是,编译器尝试使用 Integer.intValue() 来解开 i 。由于将 Integer 转换为 double 需要多个步骤 (Integer -> int -> double) 编译器拒绝隐式执行此操作,因此我们需要通过使用显式类型转换来“帮助他”,这将减少步骤数。正确吗?

Integer i = 2;
double d = 2.0;
System.out.println(i == d); // OK: true

在此示例中,编译器显然需要多个步骤来执行转换(Integer -> int -> double)。为什么它不提示?

我知道必须使用 equals() 方法而不是 ==

最佳答案

答案可以在 Java Language Specification 中找到,在 15.21. Equality Operators 部分:

The operators == (equal to) and != (not equal to) are called the equality operators.

部分15.21.1. Numerical Equality Operators == and !=说:

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).

部分15.21.3. Reference Equality Operators == and !=说:

If the operands of an equality operator are both of either reference type or the null type, then the operation is object equality.

It is a compile-time error if it is impossible to convert the type of either operand to the type of the other by a casting conversion (§5.5). The run-time values of the two operands would necessarily be unequal (ignoring the case where both values are null).

如果没有强制转换,i == d 表达式必须遵循第 15.21.3 节中的规则,因为 id 都是引用类型,而不是数字类型。只有原始类型是数字类型(当然 boolean 除外)。

由于 Integer 无法转换为 Double,并且 Double 无法转换为 Integer ,编译器知道表达式不可能为 true(忽略两个值都为 null 的情况),因此会发生编译类型错误。

当您执行(double) i == d时,左侧将变为数字类型,并且适用第15.21.1节中指定的规则。

关于java - 使用 == 运算符比较包装类和基元时类型转换背后的逻辑是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64718768/

相关文章:

python - 在 Lua 中嵌入 Python DLL 并公开函数

java - 三元运算符无法识别 Eclipse 中的编译错误

java - 哪些数据库支持同步复制(Java/嵌入式首选)?

java - Eclipse RCP - SelectionService - 历史?

c# - 在 Python 中使用 C# DLL

Java : autoboxing of an Object array of integers, 从 LinkedList.toArray() 转换为 int

java - java重载方法的搜索顺序

java - 将 jQuery 与 WebDriver 结合使用 (JAVA)

java - 如何从不可知函数调用多态函数?

python - 包装一个类,其方法返回该类的实例