Junior — Middle
What happens inside an ArrayList when inserting an element in its middle?
sobes.tech AI
Answer from AI
When inserting an element into the middle of an ArrayList, the following occurs:
-
It checks whether there is enough space in the internal array for the new element. If not, the array is resized (a new larger array is created, and all elements are copied).
-
All elements from the insertion position to the end of the list are shifted one position to the right to make space for the new element.
-
The new element is written into the freed position.
This shifting of elements is an operation with linear complexity O(n), where n is the number of elements after the insertion position. Therefore, inserting in the middle of an ArrayList is less efficient than adding at the end.
Example:
ArrayList<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));
list.add(2, 99); // insert 99 at index 2
// After insertion: [1, 2, 99, 3, 4, 5]