Why even if the declared final list of arrays can be expanded with new elements

Here is my code:

final List<String> items = new ArrayList<>();

items.add("Text name 1");
items.add("Text name 2");
items.add("Text name 3");

      

I am wondering how it is possible to expand items

with new members even if announced final

? What does it mean here final

?

+3


source to share


3 answers


final

means that this link list

is, final

that can not be changed. As you cannot assign any other list

or reinitialize this one list

.

final List<String> items = new ArrayList<>();
items = otherStringList;//ERROR
items = new ArrayList<>();//ERROR

      



JLS(Β§4.12.4)

is talking,

If the final variable contains a reference to an object, then the state of the object can be changed using operations on the object , but the variable will always refer to the same object.

+2


source


final

means that you cannot change object references items

. For example, items = new ArrayList<>()

after your initial ad is illegal.



However, you can change the properties of the object itself.

+1


source


final

means you cannot reassign items

to anotherList

0


source







All Articles