【问题标题】:Integer becomes Long when passed to the method that is expecting a Object Type当传递给期望对象类型的方法时,整数变为 Long
【发布时间】:2020-01-31 12:27:31
【问题描述】:
public class Main
{
    public static void main(String args[])
    {
        process(true ? 1 : 2L);
    }


    static void process(Object object)
    {
        System.out.println(object instanceof Integer);
    }
}

我的预期输出是 true

但实际输出是 false

我的理解是整数数据类型之间将分配最大的类型。 如果有,这叫什么?

【问题讨论】:

  • Err,为什么你会认为 1 Integer 和 2L Long ... 的“更大”类型会是 Integer?
  • 顺便说一句...请始终输入L 而不是l。关于字体,很容易被误读为1(数字)。

标签: java object integer autoboxing


【解决方案1】:

true ? 1 : 2l 的 then 和 else 部分是 intlong。结果是最宽的,long,然后部分被转换为长。见JLS

在计算机科学中,对此的一个术语是平衡类型

34 / 2.0        // double, more a case of _widening a type_.
c ? 2.0 : 34    // double

【讨论】:

【解决方案2】:

here 所述,具有intlong 的三元表达式将受到binary numeric conversion 的约束,从而产生long

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-22
    • 2018-02-12
    • 2010-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多