本文介绍了带条件表达式的数值类型提升的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在玩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)

请注意,二进制数值提升执行值集转换(§5.1.13),并可能执行取消装箱转换(§5.1.8).

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

这篇关于带条件表达式的数值类型提升的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-12 11:48