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);
It just means that you can't re-assign its reference.
Output Explanation: The array arr is declared as final, but the elements of an array are changed without any problem. Arrays are objects and object variables are always references in Java. So, when we declare an object variable as final, it means that the variable cannot be changed to refer to anything else.
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();
In essense, you can still change, add and remove the contents of the list, but cannot create a new list assigned to the variable synapses.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With