使用条件运算符的奇怪java行为。这是一个错误吗? [英] Strange java behaviour with conditional operator. Is it a bug?

查看:248
本文介绍了使用条件运算符的奇怪java行为。这是一个错误吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请你运行以下并解释一下吗?

Can you please run the below and explain?

Object o = true ? new Integer(1) : new Double(2.0);
System.out.println(o);

我发现令人惊讶的是,有人预计会打印1而不是1.0

I found that surprising as someone would expect 1 to be printed and not 1.0

推荐答案

这一点都不奇怪,虽然它看起来像是一个。该行为在 JLS§ 15.25中指定。 - 条件运算符

It's not a surprise at all, although it might seem like one. The behaviour is specified in JLS §15.25 - Conditional Operator:


否则,如果第二个和第三个操作数的类型为
convertible(第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 字节,另一个是
    类型 short ,然后条件表达式的类型是
    short

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

[...]

否则,二进制数字促销(§5.6.2)将应用于操作数
类型,条件表达式的类型是第二个和第三个操作数的提升类型

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.

请注意二进制数字促销执行值集转换(第5.113节)并且可能执行拆箱转换(第5.1.8节)。

Note that binary numeric promotion performs value set conversion (§5.1.13) and may perform unboxing conversion (§5.1.8).

所以整数 Double 类型被拆箱到各自的原始对应物 - int double ,作为二进制数字促销的过程。然后条件运算符的类型是 int double 的提升类型,即。因此结果是 1.0 。当然最终的结果会被装回 Double

So the Integer and Double types are unboxed to their respective primitive counterparts - int and double, as a process of binary numeric promotion. And then the type of the conditional operator is the promoted type of int and double, which is double. Hence the result is 1.0. And of course the final result is then boxed back to Double.

这篇关于使用条件运算符的奇怪java行为。这是一个错误吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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