What does it mean to make a collection final in Java?

What does it mean that a collection will be declared final in Java? Is it possible to add more elements to it? Is it that the elements that are already there can not be changed? Is this something else?

+6
source share
4 answers

No. It just means that the link cannot be changed.

final List list = new LinkedList(); .... list.add(someObject); //okay list.remove(someObject); //okay list = new LinkedList(); //not okay list = refToSomeOtherList; //not okay 
+7
source

You are confused between finite and immutable objects.

final β†’ You cannot change the reference to a collection (object). You can change the collection / object referenced. You can add items to the collection.

immutable β†’ You cannot change the contents of a collection / object referenced by links. You cannot add items to the collection.

+3
source

You can not do this, link FINAL

  final ArrayList<Integer> list = new ArrayList<Integer>(); ArrayList<Integer> list2 = new ArrayList<Integer>(); list=list2;//ERROR list = new ArrayList<Integer>();//ERROR 

JLS 4.12.4

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

+1
source

Creating the final variable ensures that you cannot reassign this object reference after it is assigned. f you combine the last keyword using Collections.unmodifiableList, you ge the behavi

 final List fixedList = Collections.unmodifiableList(someList); 

This leads to the fact that the list pointed to by fixedList cannot be changed. it can still be changed using the someList link (so make sure that after this binding it goes out of scope.)

A simpler example is to use a rainbow class that adds rainbow colors to a hashset

  public static class Rainbow { /** The valid colors of the rainbow. */ public static final Set VALID_COLORS; static { Set temp = new HashSet(); temp.add(Color.red); temp.add(Color.orange); temp.add(Color.yellow); temp.add(Color.green); temp.add(Color.blue); temp.add(Color.decode("#4B0082")); // indigo temp.add(Color.decode("#8A2BE2")); // violet VALID_COLORS = Collections.unmodifiableSet(temp); } /** * Some demo method. */ public static final void someMethod() { Set colors = RainbowBetter.VALID_COLORS; colors.add(Color.black); // <= exception here System.out.println(colors); } } } 
+1
source

Source: https://habr.com/ru/post/977056/


All Articles