gpt4 book ai didi

java - Java JLS 是否指定提升原始包装器类型?

转载 作者:搜寻专家 更新时间:2023-10-31 19:44:42 26 4
gpt4 key购买 nike

我对这个程序的输出有点迷惑:

public class xx {
public static void main(String[] args) throws Exception {
Number x = false ? new Long(123) : new Integer(456);
System.out.println(x + " isa " + x.getClass().getName());
}
}

这是它的输出:

456 isa java.lang.Long

编译器似乎正在将类型为 Integer 的对象“提升”为 Long,就像它通常会提升原始值一样。我从未听说过对象提升,这种行为似乎非常令人惊讶。

我的问题:根据 JLS,这真的是正确的行为吗?如果是这样的话,我希望能看到一份引用资料。

或者这是某种自动装箱疯狂的编译器错误?

我正在使用:

java version "1.8.0_60"
Java(TM) SE Runtime Environment (build 1.8.0_60-b27)
Java HotSpot(TM) 64-Bit Server VM (build 25.60-b23, mixed mode)

最佳答案

这实际上是二进制数字提升 ( JLS, Section 5.6.2 )。

When an operator applies binary numeric promotion to a pair of operands, each of which must denote a value that is convertible to a numeric type, the following rules apply, in order:

  1. If any operand is of a reference type, it is subjected to unboxing conversion (§5.1.8).

  2. 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.

    • Otherwise, if either operand is of type float, the other is converted to float.

    • Otherwise, if either operand is of type long, the other is converted to long.

    • Otherwise, both operands are converted to type int.

Binary numeric promotion is performed on the operands of certain operators:

...

  • In certain cases, the conditional operator ? : (§15.25)

因此,操作数被取消装箱,456 被扩展为 456L

此外,LongInteger 的特定情况在条件运算符 JLS Section 15.25, Table 15.25-C 的 JLS 部分中明确涵盖。

bnp(Long,Integer)

其中“bnp”表示二进制数字提升。因此,条件运算符表达式的类型为 long,它被装箱到 Long 以分配给 Number

关于java - Java JLS 是否指定提升原始包装器类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34911977/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com