Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring a List field with the final keyword

Tags:

java

list

final

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.

like image 527
Wang-Zhao-Liu Q Avatar asked Oct 26 '12 00:10

Wang-Zhao-Liu Q


People also ask

Can we declare a List as final?

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 happens if we declare List as final?

It just means that you can't re-assign its reference.

What happens when we declare List as final in Java?

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.


2 Answers

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.

like image 192
Mark P. Avatar answered Oct 10 '22 13:10

Mark P.


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.

like image 27
arshajii Avatar answered Oct 10 '22 15:10

arshajii