为什么三元运算符会意外地转换整数? [英] Why does the ternary operator unexpectedly cast integers?

查看:23
本文介绍了为什么三元运算符会意外地转换整数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在某处看到它讨论以下代码导致 objDouble,但它从左手打印 200.0一边.

I have seen it discussed somewhere that the following code results in obj being a Double, but that it prints 200.0 from the left hand side.

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

System.out.println(obj);

结果:200.0

但是,如果您在右手边放了一个不同的对象,例如BigDecimalobj的类型应该是Integer.

However, if you put a different object in the right hand side, e.g. BigDecimal, the type of obj is Integer as it should be.

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

System.out.println(obj);

结果:200

我认为其原因与将左侧转换为 double 的方式与 integer/ 相同 进行了两次比较和计算,但是这里的左右两边不是这样交互的.

I presume that the reason for this is something to do with casting the left hand side to a double in the same way that it happens for integer/double comparisons and calculations, but here the left and right sides do not interact in this way.

为什么会发生这种情况?

Why does this happen?

推荐答案

您需要阅读 Java 语言规范的第 15.25 节.

特别是:

否则,如果第二个和第三个操作数具有可转换(第 5.1.8 节)为数字类型的类型,则有几种情况:

Otherwise, if the second and third operands have types that are convertible (§5.1.8) to numeric types, then there are several cases:

  • 如果操作数之一是 byte 或 Byte 类型,另一个是 short 或 Short 类型,则条件表达式的类型为 short.
  • 如果其中一个操作数是 T 类型,其中 T 是字节、短整型或字符,而另一个操作数是一个 int 类型的常量表达式,其值可在类型 T 中表示,则 >- 条件表达式的类型是 T.
  • 如果其中一个操作数是 Byte 类型,另一个操作数是一个 int 类型的常量表达式,其值可以用 byte 类型表示,则条件表达式的类型是 byte.
  • 如果其中一个操作数是 Short 类型,而另一个操作数是 int 类型的常量表达式,其值可以用 short 类型表示,则条件表达式的类型为 short.
  • 如果操作数之一是类型;Character 和另一个操作数是一个 int 类型的常量表达式,其值可以用 char 类型表示,则条件表达式的类型为 char.
  • 否则,对操作数类型应用二进制数字提升(第 5.6.2 节),条件表达式的类型是第二个和第三个操作数的提升类型.请注意,二进制数字提升执行拆箱转换(第 5.1.8 节)和值集转换(第 5.1.13 节).

因此应用二进制数字提升, 开头:

当运算符将二进制数字提升应用于一对操作数时,每个操作数必须表示一个可转换为数字类型的值,以下规则依次适用,使用加宽转换(第 5.1.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:

  • 如果任何操作数是引用类型,则执行拆箱转换(第 5.1.8 节).然后:
  • 如果任一操作数的类型为 double,则另一个将转换为 double.

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

That's exactly what happens here - the parameter types are converted to int and double respectively, the second operand (the third in the original expression) is then of type double, so the overall result type is double.

这篇关于为什么三元运算符会意外地转换整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆