gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 13:45:16 25 4
gpt4 key购买 nike

我在某处看到它讨论了以下代码导致 obj 成为 Double,但它从左手打印 200.0边。

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

System.out.println(obj);

结果:200.0


但是,如果您将不同的对象放在右侧,例如BigDecimalobj 的类型应该是Integer

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

System.out.println(obj);

结果:200


我认为这是因为将左侧转换为 double 的方式与 integer/ 相同双重比较和计算,但是这里左右两边不是这样交互的。

为什么会这样?

最佳答案

您需要阅读 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.

这正是这里发生的事情 - 参数类型分别转换为 intdouble,第二个操作数(原始表达式中的第三个)的类型为 double,所以整体结果类型是double

关于java - 为什么三元运算符意外地转换为整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63335772/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com