If I have the following statement within a class where Synapse
is an abstract type:
private final List<Synapse> synapses;
Does final
allow me to still be able to change the state of the Synapse
objects in the List
, but prevent me from adding new Synapse
objects to the list? If I am wrong, could you please explain what final
is doing and when I should be using the keyword final
instead.
No, the final keyword does not make the list, or its contents immutable. If you want an immutable List, you should use:
List<Synapse> unmodifiableList = Collections.unmodifiableList(synapses);
What the final keyword does is prevent you from assigning a new value to the 'synapses' variable. I.e., you cannot write:
final List<Synapse> synapses = createList();
synapses = createNewList();
You can, however, write:
List<Synapse> synapses = createList();
synapses = createNewList();
final
prevents you from reassigning synapses
after you've assigned it once - you can still add/remove elements as you would normally. You can read more about the final
keyword here.
The Java Language Specification writes:
A variable can be declared final. A final variable may only be assigned to once. Declaring a variable final can serve as useful documentation that its value will not change and can help avoid programming errors.
It is a compile-time error if a final variable is assigned to unless it is definitely unassigned (§16) immediately prior to the assignment.
A blank final is a final variable whose declaration lacks an initializer.
Once a final variable has been assigned, it always contains the same value. If a final variable holds a reference to an object, then the state of the object may be changed by operations on the object, but the variable will always refer to the same object.
Therefore, if you wish to enforce that the state reachable through the variable does not change, you have to declare the variable final
, use an unmodifiable List (for instance with Collections.unmodifiableList), and make Synapse
objects immutable.
You can still change, add and remove the contents of the list, but cannot create a new list assigned to the variable.
The final implementation implies that object reference once initiated, the reference itself can never be changed but the content can of course be. Its not violating the rules at all. You have specified only one rule about the reference change which is working accordingly. If you want the values should also never change you should go for immutable lists i.e
List<String> items = Collections.unmodifiableList(Arrays.asList("a", "b", "c"));
See the following related question.
- Final variable manipulation in Java