Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

final list re- assignment

creating final list as

final List<String> list = new ArrayList<String>();

will not let me re-assign the list because list is final.

list = new ArrayList<String>(); will give compilation error.

but after insertion of 16th element , a new ArrayList must be created with capacity =oldCapacity *3/2 +1 and must be assigned to list.

how JVM allowing re-assignment of final list in this case.

like image 264
shrikant.sharma Avatar asked Jan 20 '26 15:01

shrikant.sharma


1 Answers

but after insertion of 16th element , a new ArrayList must be created with capacity =oldCapacity *3/2 +1 and must be assigned to list

No, a new backing array is created (when inserting the 11th element). The backing array is an instance variable of the ArrayList (defined as transient Object[] elementData;). The assignment is performed to that instance variable, which is not final.

A new ArrayList instance is not created, and the list variable still references the same instance.

Therefore there is no assignment to a final variable in the scenario you describe.

like image 182
Eran Avatar answered Jan 22 '26 04:01

Eran