gpt4 book ai didi

java - 如果从数组中复制最终变量,为什么 Java 需要对它进行显式强制转换?

转载 作者:IT老高 更新时间:2023-10-28 20:23:45 24 4
gpt4 key购买 nike

从下面的代码开始...

byte foo = 1;
byte fooFoo = foo + foo;

当我尝试编译此代码时,我会收到以下错误...

Error:(5, 27) java: incompatible types: possible lossy conversion from int to byte

...但是如果 foo 是最终...

final byte foo = 1;
final byte fooFoo = foo + foo;

文件将编译成功。

继续下面的代码...

final byte[] fooArray = new byte[1];
fooArray[0] = 1;

final byte foo = fooArray[0];
fooArray[0] = 127;

System.out.println("foo is: " + foo);

... 将打印

foo is: 1

... 这很好。该值被复制到最终变量中,并且不能再更改。使用数组中的值不会改变 foo 的值(如预期的那样......)。

为什么以下需要强制转换?

final byte[] fooArray = new byte[1];
fooArray[0] = 1;
final byte foo = fooArray[0];
final byte fooFoo = foo + foo;

这与该问题中的第二个示例有何不同?为什么编译器会出现以下错误?

Error:(5, 27) java: incompatible types: possible lossy conversion from int to byte

怎么会这样?

最佳答案

JLS ( §5.2 ) 具有使用常量表达式进行赋值转换的特殊规则:

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.

如果我们按照上面的链接,我们会在常量表达式的定义中看到这些:

  • Literals of primitive type and literals of type String
  • The additive operators + and -
  • Simple names (§6.5.6.1) that refer to constant variables (§4.12.4).

如果我们点击上面的第二个链接,我们会看到

A variable of primitive type or type String, that is final and initialized with a compile-time constant expression (§15.28), is called a constant variable.

因此 foo + foo 只有在 foo 是一个常量变量 时才能赋值给 fooFoo。将其应用于您的案例:

  • byte foo = 1; 没有定义一个常量变量,因为它不是final

  • final byte foo = 1; 确实定义了一个常量变量,因为它是final并且用常量表达式(原始文字)初始化。

  • final byte foo = fooArray[0]; 没有定义一个常量变量,因为它没有用一个常量表达式

注意 fooFoo 本身是否为 final 并不重要。

关于java - 如果从数组中复制最终变量,为什么 Java 需要对它进行显式强制转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43026241/

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