Pergunta de entrevista da empresa American Express

How does memory allocation of an ArrayList work? What happens if you add an element to an ArrayList when its memory allocation is reached?

Resposta da entrevista

Sigiloso

5 de jan. de 2022

For storing ArrayList in memory JVM allocates contiguous memory in heap just like an array, but the difference is an array has a fixed size whereas an ArrayList can grow. Initial Capacity - it is the size of the array to be created initially to store the elements and can be passed via constructor. If not specified, initial capacity is zero, but when we add a new element to it an array of default capaity = 10 is created. List list = new ArrayList (size); When we add new elements to the ArrayList, it first checks if it has enough space to add the new element, if it has it will just add the element to the array, if not it will create a new array 50% larger in size than current array, copy all elements to the new array and add the element to the new array. When we remove an element from the ArrayList, it moves the elements in the underlying array to fill the space created due to the removal.