How does the final
keyword not make a variable immutable? Wikipedia says it doesn't.
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
Read the rest of the Wikipedia article:
Although it's not recommended, Java allows final variables to be modified using reflection.
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.
For primitives such as
int, double, char
etc it works more as you might expect.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:
As the Wikipedia article mentions, if you are coming from C++, you must dissociate the concept of
const
intofinal
and immutable.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.