Java 三元运算 - 接受整数

Java Ternary Operations - Accepting Integer

如果我有这样的三元语法,编译器不会抛出任何编译错误:

int s = 2;
Double sdf = (s > 3 ?  new Double(12) : new Integer(12));

但是如果我有这个,它会抛出编译错误:

Required type: Double Provided: Integer

Double sdf = (s > 3 ?  new Integer(12) : new Integer(12));

发生这种情况是因为如果我们在三元运算符中使用问题中的包装原始值(IntegerFloatDouble 等),两个值都将是 拆箱并强制为普通类型。

这也可能会导致意外结果。

在第一个示例中,new Integer(12) 将转换为 double,因为它是普通类型。因此没有编译问题。

但在第二个示例中,两者都是 Integer,这与左侧类型 Double.

不兼容

示例取自 Sonar 规则描述 S2154:

Integer i = 123456789;
Float f = 1.0f;
// Assume condition = true
Number n = (condition) ? i : f; // i is coerced to float. n = 1.23456792E8

要解决这个问题,我们需要进行显式转换:

Integer i = 123456789;
Float f = 1.0f;
// Assume condition = true
Number n = condition ? (Number) i : f;  // n = 123456789

附加建议:不要使用 new Double()new Integer() 等。这些构造函数已弃用。而是使用 valueOf 方法

根据Conditional Operator ? : specification, in case if one operand is Integer and the other is Double binary numeric promotion是用来解析结果类型的

根据规则,在第一个示例中,结果类型为 Integer,但在第二个示例中为 Double(拆箱 + 加宽)。

这是因为内部类型被提升了。整数可以被提升为两倍。但是 double 不能降级为 Integer。 促销发生在以下方式 字节-->短整型-->整数-->长整型-->浮点型-->双精度