Declaring a List field with the final keyword

final, java, list

Solution

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.

Problem

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.

Original source

Related problems