Junior — Middle
What happens when a new element is added at the first index of an ArrayList?
sobes.tech AI
Answer from AI
When adding a new element at the first index of an ArrayList, all existing elements are shifted to the right to make space for the new element. This means that elements with indices 0, 1, 2, and so on are moved to indices 1, 2, 3, etc.
Because of this, the insertion operation at the beginning of the list has a time complexity of O(n), where n is the number of elements in the list.
Example:
ArrayList<String> list = new ArrayList<>();
list.add("b");
list.add("c");
list.add(0, "a"); // inserting "a" at the beginning
// Now the list contains: ["a", "b", "c"]