final list re- assignment

Viewed 100

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.

4 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.

No. ArrayList wont get replaced. Backed array gets expand, accordingly.

While adding element to the list, ArrayList make sure that it have enough capacity

public boolean add(E e) {
378         ensureCapacity(size + 1);  // Increments modCount!!
379         elementData[size++] = e;
380         return true;
381     }

Here is the source code of ensuring capacity. If needed, it gets expand.

public void ensureCapacity(int minCapacity) {
179         modCount++;
180         int oldCapacity = elementData.length;
181         if (minCapacity > oldCapacity) {
182             Object oldData[] = elementData;
183             int newCapacity = (oldCapacity * 3)/2 + 1;
184             if (newCapacity < minCapacity)
185                 newCapacity = minCapacity;
186             // minCapacity is usually close to size, so this is a win:
187             elementData = Arrays.copyOf(elementData, newCapacity);
188         }
189     }

And also if, list is final, you can't reassign it. However you can still add modify it's internal things through methods.

ArrayList contains an object array as its property. When the list "expands", it actually the array object expanding, hence the array is re-created (address change) but not the ArrayList itself.

Related