Sobes.tech
Junior — Middle

What operations occur inside ArrayList when adding an element at the beginning of the collection, if the internal array does not exceed its current boundary?

sobes.tech AI

Answer from AI

When adding an element to the beginning of an ArrayList, if the internal array does not exceed its current capacity, all existing elements are shifted one position to the right to make space for the new element at index 0. This is implemented using System.arraycopy, which copies elements from position 0 to the current length into position 1 and onwards. After the shift, the new element is written at index 0, and the collection size is increased by 1.

Here's an example:

// Internal array: elementData
// size - current size
System.arraycopy(elementData, 0, elementData, 1, size);
elementData[0] = newElement;
size++;

This operation has a time complexity of O(n), where n is the number of elements, since all elements are shifted by one position.

What operations occur inside ArrayList when adding an… - sobes.tech