final
关键字如何不使变量不可变? 维基百科称它不能。
final ArrayList<String> arr = new ArrayList<String>();
arr.add("hello"); // OK, the object to which arr points is mutated
arr = null; // Not OK, the reference is final and cannot be reassigned to
正如维基百科文章所提到的那样,如果你来自于C++,你必须将const
这个概念分化成final
和immutable。
阅读维基百科文章的其余部分:
为了说明最终性并不保证不可变性:假设我们用一个单一的变量替换三个位置变量: public final Position pos; 其中pos是一个具有三个属性pos.x、pos.y和pos.z的对象。然后,pos不能被赋值,但是这三个属性可以被赋值,除非它们本身是final的。
因为如果一个引用是final的,你仍然可以更改引用所指向的对象中的内容。你只是不能更改引用本身。
对于像 int, double, char
等基本类型,它的工作方式更符合您的预期。
private final int status = 10;
status = 20; // WONT COMPILE because status is final