0

Suppose we've taken an ArrayList as final.

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

Next, we've added 10 elements to it. As we all know the default initial capacity of an ArrayList is 10. So, what will happen when we add the 11th element ? --> It'll create a new ArrayList of capacity = (currentCapacity * 1.5) i.e. 15, copy all the elements from the initial ArrayList object to this new ArrayList, and then point the reference "list" to this new ArrayList object. Eventually, Old ArrayList will be Garbage Collected.

But, the question is, since we've declared the ArrayList reference "list" as final, that means reinitialization of "list" is also not allowed ("list" was initially pointing to the ArrayList Object of capacity 10 --> then "list" will point to the ArrayList Object of capacity 15).

So, how is it that it'll still work fine and what is the logic behind it?

Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
  • 2
    *"So, what will happen when we add the 11th element ? --> It'll create a new ArrayList"* no, that's not what happens. It creates a new arary *inside* the `ArrayList`. – Federico klez Culloca Jul 20 '22 at 15:27
  • 2
    A lot of your assumptions are wrong. eG "It'll create a new ArrayList of capacity = (currentCapacity * 1.5) i.e. 15, copy all the elements from the initial ArrayList object to this new ArrayList" <- This will never happen. What happens is that the Array the ArrayList uses internally will be recreated. But just because you declared the ArrayList final doesn't mean all it's internally used fields/local variables etc are suddenly also final. – OH GOD SPIDERS Jul 20 '22 at 15:28
  • 1
    Right, only the reference to the ArrayList is final. The ArrayList itself is allowed to have fields (heap memory) that are not final. The `final` keyword does not somehow propagate through the entire object, final references can still point to mutable objects. Internally the ArrayList has a field (`class ArrayList { Object[] items;}` that is updated when the ArrayList changes size, not the reference you see. – markspace Jul 20 '22 at 15:35

0 Answers0