How does the final
keyword not make a variable immutable? Wikipedia says it doesn't.
问题:
回答1:
In Java, the term final refers to references while immutable refers to objects. Assigning the final
modifier to a reference means it cannot change to point to another object, but the object itself can be modified if it is mutable.
For example:
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
As the Wikipedia article mentions, if you are coming from C++, you must dissociate the concept of const
into final
and immutable.
回答2:
Although it's not recommended, Java allows final variables to be modified using reflection.
回答3:
Suppose you have declared that myList is final. You can still add new items to myList, so its state is NOT immutable. What you can't do, because of the final keyword, is to change myList to refer to a different list.
回答4:
Read the rest of the Wikipedia article:
To illustrate that finality doesn't guarantee immutability: suppose we replace the three position variables with a single one: public final Position pos; where pos is an object with three properties pos.x, pos.y and pos.z. Then pos cannot be assigned to, but the three properties can, unless they are final themselves.
回答5:
because if a reference is final, you can still change things in the object to which the reference points. You just cant change the reference.
回答6:
For primitives such as int, double, char
etc it works more as you might expect.
private final int status = 10;
status = 20; // WONT COMPILE because status is final