我的应用程序中有这段代码(简化版):
Object result;
if (check)
result = new Integer(1);
else
result = new Double(1.0);
System.out.println(result);
return result;
然后我决定将 if-else 语句重构为三元条件表达式,这样我的代码就更简洁了:
Object result = check ? new Integer(1) : new Double(1.0);
System.out.println(result);
return result;
事实证明,如果检查为 true
,两个版本会打印不同的结果:
1
或:
1.0
三元条件不是等价于对应的if-else吗?
最佳答案
if/else 和条件(三元)表达式不完全等效。条件表达式的结果必须有类型。
您正在观察数字类型提升(或类型强制)的效果。
这是语言规范的摘录(参见 here),来自描述条件表达式的返回值的部分:
Otherwise, if the second and third operands have types that are convertible (§5.1.8) to numeric types, then there are several cases:
最后一种情况是(我在这里省略了其他情况):
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.
这是与二进制数字提升相关的附加规范:
Widening primitive conversion (§5.1.2) is applied to convert either or both operands as specified by the following rules:
- If either operand is of type double, the other is converted to double.
这是第一种情况(以下情况省略)。 double
总是赢。
所以无论你的条件表达式中第二个和第三个操作数的顺序如何,表达式的返回类型都会被提升为double
。
关于java - Java中带盒装类型的三元条件的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30279118/