3

Please consider my question. final values cannot be changed in java.

private final List<Integer> list = new ArrayList<Integer>();

above list instantiation is of final. now i can add any elements. after that can i assign list=null?

Please help me.

Thanks!

user1016403
  • 12,151
  • 35
  • 108
  • 137
  • Possible duplicate of [When should one use final?](http://stackoverflow.com/questions/154314/when-should-one-use-final) – Beau Grantham Dec 23 '11 at 17:07
  • Its more a duplicate of this http://stackoverflow.com/questions/4525642/java-final-arraylist then the link you posted @BeauGrantham. – Perception Dec 23 '11 at 17:10

4 Answers4

2

That means the variable list is final.

Which means you can not assign something else to it again.

Once you are done assign a value (reference) to it as follows:

private final List<Integer> list = new ArrayList<Integer>();

You can not do something as below again:

list = new ArrayList<Integer>(); //this is invalid because you are trying to assign something else the variable list

list.add(new Integer(123)); is this code valid?

It's perfectly valid. You are just adding an object to the ArrayList that variable list is referencing.

The usage of final keyword is restricting the variable list not the ArrayList object that it's referencing.

Mike Samuel
  • 118,113
  • 30
  • 216
  • 245
Bhesh Gurung
  • 50,430
  • 22
  • 93
  • 142
1

The new keyword in Java creates a new Object and returns its reference. Hence, in your code, the list variable stores the reference to the new list. Declaring it final means that the reference stored in list is final, and cannot be changed.

The actual list is still modifiable.

Danish
  • 3,708
  • 5
  • 29
  • 48
1

The final keyword indicates that a variable can only be initialized once. It does not guarantee immutability of the object assigned to that variable. In other words, it says something about what a variable can refer to, but nothing about the contents of the referent.

Wayne
  • 59,728
  • 15
  • 131
  • 126
1

For your code and if you have this:

private final List<Integer> list = new ArrayList<Integer>();

This is possible:

list.add(3);

This is not allowed:

list = new ArrayList<Integer>();
Adel Boutros
  • 10,205
  • 7
  • 55
  • 89