-3

Declaring a collection final doesn't suppress any of its functionality (still can add, remove, clear, get, etc.) but allows the compiler to optimise more.

In what scenario is it preferable to change the reference (disallowing the use of final) rather than use the methods of the existing collection?

apilat
  • 1,370
  • 8
  • 17
  • similar to https://stackoverflow.com/questions/26500423/what-does-it-mean-for-a-collection-to-be-final-in-java – RAZ_Muh_Taz Apr 10 '18 at 15:36
  • Possible duplicate of [Why can final object be modified?](https://stackoverflow.com/questions/2435163/why-can-final-object-be-modified) –  Apr 10 '18 at 15:37
  • 1
    Everything should be `final` unless its reference might change. – Michael Apr 10 '18 at 15:37
  • A web search of "java final collections" should get you everything you need. –  Apr 10 '18 at 15:38

2 Answers2

1

You shouldn't declare a variable final if you wish to modify its value at a later date. In the case of collections, if you are planning on replacing the entire reference to the collection, then it's fine to not mark it as final.

// Plan to change collection
List<Integer> intVals = new ArrayList<>();

// later in your code
intVals = getOtherValuesInstead();

You should declare it final if you absolutely do not want the reference to change. This is the more typical approach; as you describe correctly, since you can add values to the collection anyway, you shouldn't find yourself in a scenario where you have to change its reference.

Makoto
  • 104,088
  • 27
  • 192
  • 230
0

When should a Java collection not be declared final?

In almost every case except when you specifically want to be certain that the object will never be changed.

You should only use final when you need to. There are many situations when you do need to but you should not use final by default.

OldCurmudgeon
  • 64,482
  • 16
  • 119
  • 213
  • Why that? Imo it's totally opinion based and there is no good or bad practice to it. I met programmers that do it this or that way. I personally use the most restrictive modifiers as possible as long as I don't need anything different. So `final` and `private` everywhere until I need something different. – Zabuzard Apr 10 '18 at 16:13
  • @Zabuza - You are correct - it is significantly opinion based. IMHO using `final` when unnecessary is just clutter. I have seen code that made **all** parameters in **all** methods `final` and it was horrendous to grok. – OldCurmudgeon Apr 10 '18 at 16:16