Java条件赋值中的类型错误 [英] Wrong type in Java conditional assignment

查看:246
本文介绍了Java条件赋值中的类型错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码中,我有两个相同的条件赋值操作,一个返回Double类型的对象,第二个返回字符串Integer。

In the following code I have two identical conditional assignment operations, one returns an object of type Double, and the second returns the String "Integer".

double d = 24.0;

Number o = (d % 1 == 0) ? new Double(d).intValue() : new Double(d).doubleValue();
String result = (d % 1 == 0) ? "Integer" : "Double";

System.out.println(o.getClass()); // prints "class java.lang.Double"
System.out.println(result); // Integer

为什么完全相同的表达式返回两个不同的东西?

Why are the exact same expressions returning two different things?

推荐答案

那是因为条件运算符的JLS规范


否则,如果第二个和第三个操作数的类型可以转换(第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:


  • ...

  • 否则,二进制数字促销(§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.

数字促销在此处定义< a href =http://docs.oracle.com/javas e / specs / jls / se7 / html / jls-5.html#jls-5.6.2rel =noreferrer>§5.6.2。它说:

Numeric promotion is defined here in §5.6.2. It says:


应用扩展原始转换(第5.1.2节)来转换两个操作数或
两个操作数遵循以下规则:

Widening primitive conversion (§5.1.2) is applied to convert either or both operands as specified by the following rules:


  • 如果任一操作数的类型为double,则另一个操作数转换为double。

  • ...

这篇关于Java条件赋值中的类型错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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