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.
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
See the following related question.
No, the final keyword does not make the list, or its contents immutable. If you want an immutable List, you should use:
What the final keyword does is prevent you from assigning a new value to the 'synapses' variable. I.e., you cannot write:
You can, however, write:
The Java Language Specification writes:
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 makeSynapse
objects immutable.final
prevents you from reassigningsynapses
after you've assigned it once - you can still add/remove elements as you would normally. You can read more about thefinal
keyword here.