gpt4 book ai didi

java - Numbers 上不需要的自动装箱魔法

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:45:26 25 4
gpt4 key购买 nike

下面的程序分别打印'false'和'true':

Number n = true ? new Long(1) : new Double(2.0);
System.out.println(n instanceof Long);
System.out.println(n instanceof Double);

所以它不会是 Long 而是 Double。但是,它在普通类上按预期工作:拥有

class B {}
class D1 extends B {}
class D2 extends B {}

这将打印“真”:

B b = true ? new D1() : new D2();
System.out.println(b instanceof D1);

这意味着它与上面的示例不同。

我确定有一些与自动装箱有关的东西,但它真的应该这样工作吗?当 Number 类是 Long 和 Double 的父类(super class)时,她为什么要使用装箱,以便表达式可以计算为 Number?

这真的很痛苦,因为打印 n 时,它打印为 double 值。 (我知道这很容易解决,但让我抓狂)

最佳答案

这里把语言律师的书拿出来:JLS §15.25

The type of a conditional expression is determined as follows:

  • If the second and third operands have the same type (which may be the null type), then that is the type of the conditional expression.

Long 和 Double 不是同一类型 - 不适用。

  • If one of the second and third operands is of primitive type T, and the type of the other is the result of applying boxing conversion (§5.1.7) to T, then the type of the conditional expression is T.

这两个值都不是原始值 - 不适用。

  • If one of the second and third operands is of the null type and the type of the other is a reference type, then the type of the conditional expression is that reference type.

两个值都不为空 - 不适用。

  • Otherwise, if the second and third operands have types that are convertible (§5.1.8) to numeric types, then there are several cases:
    • [... special cases for byte/short/char and their boxed equivalents...]
    • 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.

这条规则在这里确实适用,这意味着条件运算符的结果类型就像两个值都被取消装箱一样。假设其背后的原因是否则 Number n = bool ? 1 : 2.0Number n = bool ? new Long(1) : new Double(2.0) 有不同的值。这种行为也会出乎意料,甚至更糟 - 不一致。

关于java - Numbers 上不需要的自动装箱魔法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12788865/

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