带条件表达式的数值类型提升
我在玩Java,发现了一些东西.最好在这里显示:
I was toying around with java, and I noticed something. It can be best shown here:
boolean boo = true;
Object object1 = boo ? new Integer(1) : new Double(2.0);
Object object2;
if (boo)
object2 = new Integer(1);
else
object2 = new Double(2.0);
System.out.println(object1);
System.out.println(object2);
我希望两者是一样的,但这就是打印出来的内容:
I would expect the two to be the same, but this is what gets printed:
1.0
1
有人对此有很好的解释吗?
Does anyone have a good explanation for this?
三元组在两种情况下都必须返回相同的类型,因此您的第一个结果( Integer
)被提升为 转换为Double,以匹配 2.0
.另请参见
A ternary must return the same type for both conditions, so your first result (Integer
) is promoted to a double to match 2.0
. See also,
Object object1 = boo ? new Integer(1) : new Double(2.0);
System.out.println(object1.getClass().getName());
此文档记录在 JLS-15.25.2-数值条件表达式读取(部分显示)
This is documented at JLS-15.25.2 - Numeric Conditional Expressions which reads (in part)
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.1.8).
Note that binary numeric promotion performs value set conversion (§5.1.13) and may perform unboxing conversion (§5.1.8).