0

Which advantages/disadvantages of making ArrayList (or other Collection) final? And what if we try to do so like:

final List<Integer> A=new ArrayList<Integer>(1,2,3,4,5);
List<Integer> l=new ArrayList<Integer>(4,8,16);
A=l;

Is this is valid? Now the reference A will point to this Array list pointed by l? Please help.

Timothy Truckle
  • 15,071
  • 2
  • 27
  • 51
  • 3
    1) `final` *affects the variable*, and not the object to which is refers. 2) It is not *not allowed* to re-assign to a `final` variable. The compiler should have said as much. – user2864740 Jan 08 '18 at 21:04
  • 1
    https://stackoverflow.com/a/10380512/2864740 (this answer is more generalized than the question) , https://stackoverflow.com/questions/15655012 (specific to final fields, discusses object mutability as well) – user2864740 Jan 08 '18 at 21:07
  • 1
    Also, `ArrayList` does not have a constructor that will allow that usage. – Louis Wasserman Jan 08 '18 at 21:09
  • ok thanks a lot for help guys :) – gaurav joshi Jul 21 '18 at 08:44

1 Answers1

1

No, reassignment to final reference is not allowed in Java.

niemar
  • 612
  • 1
  • 7
  • 16