List field declaration with final keyword

If I have the following statement in a class where Synapse is an abstract type:

 private final List<Synapse> synapses; 

Does final allow me to change the state of Synapse objects in a List , but it does not allow me to add new Synapse objects to the list? If I am mistaken, could you please explain what final does and when I should use the final keyword.

+8
java list final
source share
5 answers

No, the last keyword does not make the list, or its contents unchanged. If you want an immutable list, you should use:

 List<Synapse> unmodifiableList = Collections.unmodifiableList(synapses); 

What the last keyword does does not allow us to assign a new value to the synapses variable. Ie you cannot write:

 final List<Synapse> synapses = createList(); synapses = createNewList(); 

You can, however, write:

 List<Synapse> synapses = createList(); synapses = createNewList(); 
+20
source share

final does not allow you to reassign synapses after you have assigned it once - you can still add / remove items as usual. Read more about the final keyword here .

+4
source share

You can still modify, add, and delete the contents of a list, but you cannot create a new list assigned to a variable.

+2
source share

The Java language specification writes :

A variable can be declared final. The final variable can only be assigned once. Declaring a final variable can serve as useful documentation that its value will not change and will help to avoid programming errors.

This is a compile-time error if a final variable is assigned, if it is definitely not assigned (Β§16) immediately before the assignment.

An empty ending is a final variable in the declaration of which there is no initializer.

Once a final variable has been assigned, it always contains the same value. If the final variable contains a reference to the object, then the state of the object can be changed by operations on the object, but the variable will always refer to the same object.

Therefore, if you want to ensure that state accessibility through a variable does not change, you must declare the final variable, use an unmodifiable list (e.g. Collections.unmodifiableList ), and make Synapse objects immutable.

+2
source share

The final implementation implies that the link to the object is immediately initiated, the link itself can never be changed, but, of course, there may be content. This does not violate the rules at all. You have specified only one rule regarding a reference change that works accordingly. If you want the values ​​to never change either, you should go to immutable lists i.e.

 List<String> items = Collections.unmodifiableList(Arrays.asList("a", "b", "c")); 

See the following related question.

  • Java Variable Processing Complete
+1
source share

All Articles