java - Java 条件表达式中的错误行为

标签 java language-design conditional-operator autoboxing

一个简单的表达式:

Object val = true ? 1l : 0.5;

val 是什么类型?那么,从逻辑上讲,val 应该是一个值为 1Long 对象。但 Java 认为 val 是一个 Double,其值为 1.0

它不必像自动装箱那样做任何事情

Object val = true ? new Long(1) : new Double(0.5);

结果具有相同的行为。

只是为了澄清:

Object val = true ? "1" : 0.5;

产生正确的字符串

有人可以解释一下为什么他们这样定义吗?对我来说,它的设计似乎相当糟糕,或者实际上是一个错误。

最佳答案

Java 语言规范 Section 15.25 对此进行了描述(相关部分以粗体显示):

The type of a conditional expression is determined as follows:

  1. If the second and third operands have the same type [...]

  2. If one of the second and third operands is of type boolean [...]

  3. If one of the second and third operands is of the null type [...]

  4. Otherwise, if the second and third operands have types that are convertible (§5.1.8) to numeric types, then there are several cases:

    1. If one of the operands is of type byte [...]

    2. If one of the operands is of type T where T is byte, short, or char, [...]

    3. If one of the operands is of type Byte [...]

    4. If one of the operands is of type Short [...]

    5. If one of the operands is of type; Character [...]

    6. 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. Note that binary numeric promotion performs unboxing conversion (§5.1.8) and value set conversion (§5.1.13).

  5. Otherwise, the second and third operands are of types S1 and S2 respectively. Let T1 be the type that results from applying boxing conversion to S1, and let T2 be the type that results from applying boxing conversion to S2. The type of the conditional expression is the result of applying capture conversion (§5.1.10) to lub(T1, T2) (§15.12.2.7).

上一段中提到的“lub”代表最小上限,指的是 T1 和 T2 常见的最具体的父类(super class)型。

<小时/>

至于Object val = true 的情况? 1l : 0.5; 我同意如果应用规则 5(在盒装值上)会更精确。我想当考虑到自动装箱时,规则会变得模糊(甚至更加复杂)。例如,表达式 b 是什么类型? new Byte(0) : 0.5 有吗?

但是,您可以通过执行以下操作强制它使用规则 5

Object val = false ? (Number) 1L : .5;

关于java - Java 条件表达式中的错误行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6506751/

相关文章:

java ? : operator in vb. 网络

java - 在 Java 中节省纪元时间的最佳方法是什么?

Java 8 实例创建注解

java - 递归问题

scala - scala.Singleton 是纯编译器小说吗?

C# - 在三元运算符中呈现部分

c - 在 C 中使用条件语句打印多个格式化字符串

java - 接口(interface)API总是不变的吗?

c - 为什么 C I/O 函数之间不一致?

language-design - 为什么 COBOL 同时具有 `SECTION` 和 `PARAGRAPH` ?