gpt4 book ai didi

java - 为什么在自动装箱期间发生 final long 到 Byte 的编译错误,但 final int 到 Byte 是可以的?

转载 作者:太空狗 更新时间:2023-10-29 22:54:55 26 4
gpt4 key购买 nike

intshort 类型的常量自动装箱到 Byte 时没有错误,但 long< 的常量 类型 do 有错误。为什么?

final int i = 3;
Byte b = i; // no error

final short s = 3;
Byte b = s; // no error


final long l = 3;
Byte b = l; // error

最佳答案

来自 JLS Sec 5.2, "Assignment contexts" (强调我的):

In addition, if the expression is a constant expression (§15.28) of type byte, short, char, or int:

  • A narrowing primitive conversion may be used if the type of the variable is byte, short, or char, and the value of the constant expression is representable in the type of the variable.

  • A narrowing primitive conversion followed by a boxing conversion may be used if the type of the variable is:

    • Byte and the value of the constant expression is representable in the type byte.
    • ...

规范根本不允许 long

请注意,这里的第二个要点表示无论装箱如何都会发生这种情况:将常量 long 表达式分配给 byte 变量同样会失败:

// Both compiler errors.
byte primitive = 0L;
Byte wrapped = 0L;

关于java - 为什么在自动装箱期间发生 final long 到 Byte 的编译错误,但 final int 到 Byte 是可以的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46206288/

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