<分区>
Object myObject = true ? new Integer(25) : new Double(25.0);
System.out.println(myObject);
奇怪的是,它输出的是 25.0 而不是 25
这是怎么回事?
<分区>
Object myObject = true ? new Integer(25) : new Double(25.0);
System.out.println(myObject);
奇怪的是,它输出的是 25.0 而不是 25
这是怎么回事?
最佳答案
您的代码按预期返回第二个操作数 (new Integer(25)
),但由于以下规则,它会将其转换为 Double
。
这是JLS 15.25说:
if the second and third operands have types that are convertible (§5.1.8) to numeric types, then there are several cases:
- If one of the operands is of type byte or Byte and the other is of type short or Short, then the type of the conditional expression is short.
- If one of the operands is of type T where T is byte, short, or char, and the other operand is a constant expression (§15.28) of type int whose value is representable in type T, then the type of the conditional expression is T.
- If one of the operands is of type T, where T is Byte, Short, or Character, and the other operand is a constant expression (§15.28) of type int whose value is representable in the type U which is the result of applying unboxing conversion to T, then the type of the conditional expression is U.
- Otherwise, binary numeric promotion (§5.6.2) is applied to the operand types, and the type of the conditional expression is the promoted type of the second and third operands.
Note that binary numeric promotion performs value set conversion (§5.1.13) and may perform unboxing conversion (§5.1.8).
以及数字促销:
5.6.2. Binary Numeric Promotion
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:
If any operand is of a reference type, it is subjected to unboxing conversion (§5.1.8).
Widening primitive conversion (§5.1.2) is applied to convert either or both operands as specified by the following rules:
If either operand is of type double, the other is converted to double.
在您的示例中,您有一个Integer
和一个Double
。它们被拆箱为 int
和 double
,然后 int
被转换为 double
。
关于java - 为什么条件运算符的结果与预期相反?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27634241/