3

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'm curios as to how it is possible to extend items with new members even if it is declared final? What does final here mean than?

Max Koretskyi
  • 101,079
  • 60
  • 333
  • 488
  • 1
    Final here means the reference is final not the items in the list. โ€“ akhil_mittal May 02 '15 at 06:06
  • 1
    in ths case final mens that you cant assign new value to your **items** variable. To **disable modifying values** you can use [Collections.unmodifiableList](http://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#unmodifiableList-java.util.List-) โ€“ cache May 02 '15 at 07:13

3 Answers3

3

final means reference of this list is final which can not be changed.As you can not assign any other list or reinitialize this list.

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

JLS(ยง4.12.4) says,

If a final variable holds a reference to an object, then the state of the object may be changed by operations on the object, but the variable will always refer to the same object.

akash
  • 22,664
  • 11
  • 59
  • 87
1

final means that you can't change the object items references. For example, items = new ArrayList<>() after your initial declaration would be illegal.

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

fdsa
  • 1,379
  • 1
  • 12
  • 27
0

final just means that you cannot reassign items to another List

Transcendence
  • 2,616
  • 3
  • 21
  • 31