What does it mean for a collection to be declared final in Java? Is it that no more elements can be added to it? Is it that the elements already there cannot be changed? Is it something else?
-
2It means that it's reference (that of the list) can't be changed – MadProgrammer Oct 22 '14 at 04:41
-
See also: [what is the sense of final ArrayList?](http://stackoverflow.com/q/10750791/697449), [Declaring a List field with the final keyword](http://stackoverflow.com/q/13079365/697449), [Java final modifier](http://stackoverflow.com/q/4012167/697449) – Paul Bellora Oct 22 '14 at 04:51
4 Answers
No. It simply means that the reference 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

- 31,565
- 17
- 75
- 112
You are getting confused between final and immutable Objects.
final
--> You cannot change the reference to the collection (Object). You can modify the collection / Object the reference points to. You can still add elements to the collection
immutable
--> You cannot modify the contents of the Collection / Object the reference points to. You cannot add elements to the collection.

- 35,966
- 12
- 68
- 104
You can't do this,the reference is FINAL
final ArrayList<Integer> list = new ArrayList<Integer>();
ArrayList<Integer> list2 = new ArrayList<Integer>();
list=list2;//ERROR
list = new ArrayList<Integer>();//ERROR
Once a final variable has been assigned, it always contains the same value. 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.

- 22,664
- 11
- 59
- 87
Making the variable final makes sure you cannot re-assign that object reference after it is assigned. If you combine the final keyword with the use of Collections.unmodifiableList, you get the behaviour that you describe:
final List fixedList = Collections.unmodifiableList(someList);
This has as result that the list pointed to by fixedList cannot be changed. it can still be change through the someList reference (so make sure it is out of scope after this asignment.)
More simple example is taking a rainbow class adding colors of rainbow in 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,017
- 15
- 23

- 4,499
- 4
- 31
- 60