java – 为什么三元运算符意外地转换整数?

我已经看到它讨论了某个地方,下面的代码导致obj是一个双,但它从左侧打印200.0。

Object obj = true ? new Integer(200) : new Double(0.0);

System.out.println(obj);

结果:200.0

然而,如果你把一个不同的对象在右手边,例如。 BigDecimal,obj的类型是整数,因为它应该是。

Object obj = true ? new Integer(200) : new BigDecimal(0.0);

System.out.println(obj);

结果:200

我认为这个原因与将左手边转换为double的原因相同,就像整数/双精度比较和计算一样,但是这里左边和右边不以这种方式交互。

为什么会发生这种情况?

最佳答案
你需要阅读section 15.25 of the Java Language Specification

尤其是:

Otherwise, 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 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 Byte and the other operand is a constant expression of type int whose value is representable in type byte, then the type of the conditional expression is byte.
  • If one of the operands is of type Short and the other operand is a constant expression of type int whose value is representable in type short, then the type of the conditional expression is short.
  • If one of the operands is of type; Character and the other operand is a constant expression of type int whose value is representable in type char, then the type of the conditional expression is char.
  • 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 unboxing conversion (§5.1.8) and value set conversion (§5.1.13).

所以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, 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. Then:
  • If either operand is of type double, the other is converted to double.

这正是这里发生的事情 – 参数类型分别转换为int和double,第二个操作数(原始表达式中的第三个)的类型为double,因此整体结果类型为double。

转载注明原文:java – 为什么三元运算符意外地转换整数? - 代码日志