为什么我可以在Java中编辑最终数组的内容?
以下 Java 代码使用 .final
String
final public class Main {
public static final String[] CONSTANT_ARRAY = {"I", "can", "never", "change"};
public static void main(String[] args) {
for (int x = 0; x < CONSTANT_ARRAY.length; x++) {
System.out.print(CONSTANT_ARRAY[x] + " ");
}
}
}
它在控制台上显示以下输出。
I can never change
如果我们尝试重新分配类型 为 的声明数组,我们会导致错误:final
String
final public class Main {
public static final String[] CONSTANT_ARRAY = {"I", "can", "never", "change"};
public static void main(String[] args) {
CONSTANT_ARRAY={"I", "can", "never", "change"}; //Error - can not assign to final variable CONSTANT_ARRAY.
for (int x = 0; x < CONSTANT_ARRAY.length; x++) {
System.out.print(CONSTANT_ARRAY[x] + " ");
}
}
}
错误:无法分配给最终变量 。
CONSTANT_ARRAY
但是,以下代码有效:
final public class Main {
public static final String[] CONSTANT_ARRAY = {"I", "can", "never", "change"};
public static void main(String[] args) {
CONSTANT_ARRAY[2] = "always"; //Compiles fine.
for (int x = 0; x < CONSTANT_ARRAY.length; x++) {
System.out.print(CONSTANT_ARRAY[x] + " ");
}
}
}
它显示
I can always change
这意味着我们可以设法修改类型.我们能否以这种方式修改整个数组,而不会违反 不可变的规则 ?final
String
final