gpt4 book ai didi

java - 包装类 - 为什么整型文字对 Long 失败但对任何更小的东西都有效

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

我只是想了解自动装箱,除了一件事:

Short s = 250;
Long l = 250;

Long l 的赋值失败。我预计,这是因为你不能加宽 then box(即它试图将 int250 加宽到 long 然后将其装箱这是它做不到的)。

但是,对 Short s 的赋值是有效的。是什么让这一切变得美好?我的假设是它仍在进行装箱和某种转换。但是,如果它知道 250 适合 short,为什么它不知道 250 适合 long ?

最佳答案

通常,您不能在赋值 ( JLS §5.2 Assignment Conversion ) 中应用多个(隐式)转换:

Assignment conversion occurs when the value of an expression is assigned (§15.26) to a variable: the type of the expression must be converted to the type of the variable. Assignment contexts allow the use of one of the following:

  • an identity conversion (§5.1.1)
  • a widening primitive conversion (§5.1.2)
  • a widening reference conversion (§5.1.5)
  • a boxing conversion (§5.1.7) optionally followed by a widening reference conversion
  • an unboxing conversion (§5.1.8) optionally followed by a widening primitive conversion.

Long l=250; 需要两次转换(加宽原始转换,然后是装箱转换),这就是它无法编译的原因。

Long l=250l; 可以编译,因为它需要一次装箱转换。

但是常量表达式的收缩转换是一种特殊情况,这就是为什么 Short s=250; 编译:

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.
    • Short and the value of the constant expression is representable in the type short.
    • Character and the value of the constant expression is representable in the type char.

关于java - 包装类 - 为什么整型文字对 Long 失败但对任何更小的东西都有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14425606/

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