gpt4 book ai didi

java - 为什么 Long (Wrapper) 在转换为字节时没有拆箱为原始 long?

转载 作者:行者123 更新时间:2023-12-02 15:04:16 24 4
gpt4 key购买 nike

为什么Long(包装器)不拆箱为原始长整型,然后转换为原始字节?

Long lo = 4L;

byte b = (byte) lo; // c.ERR !!!

Byte bW = (byte) lo; // c.ERR !!!

最佳答案

因为 Java 语言规范是这么说的!

JLS § 5.5 Casting Contexts

Casting contexts allow the use of one of:

  • an identity conversion (§5.1.1)

  • a widening primitive conversion (§5.1.2)

  • a narrowing primitive conversion (§5.1.3)

  • a widening and narrowing primitive conversion (§5.1.4)

  • a widening reference conversion (§5.1.5) optionally followed by either an unboxing conversion (§5.1.8) or an unchecked conversion (§5.1.9)

  • a narrowing reference conversion (§5.1.6) optionally followed by either an unboxing conversion (§5.1.8) or an unchecked conversion (§5.1.9)

  • a boxing conversion (§5.1.7) optionally followed by a widening reference conversion (§5.1.5)

  • an unboxing conversion (§5.1.8) optionally followed by a widening primitive conversion (§5.1.2).

  • Value set conversion (§5.1.13) is applied after the type conversion.

上面的列表不包含您在此处尝试执行的转换,即拆箱转换(Longlong),然后是缩小转换( >长字节)。有趣的是,如果您缩小范围然后拆箱,这是允许的!

本节后面的表格也显示了这一点:

enter image description here

最后一行是 -,不允许进行强制转换。

关于java - 为什么 Long (Wrapper) 在转换为字节时没有拆箱为原始 long?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49444274/

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