Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what does below java line indicates with final modifier assigned to list?

Tags:

java

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!

like image 876
user1016403 Avatar asked Jul 25 '26 17:07

user1016403


1 Answers

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.

like image 105
Bhesh Gurung Avatar answered Jul 28 '26 06:07

Bhesh Gurung