Junior — Middle
How is an element removed from an ArrayList collection in Java?
sobes.tech AI
Answer from AI
Removing an element from an ArrayList in Java is done as follows:
- Find the index of the element to be removed (if removing by object, first find the index).
- All elements after the removed element are shifted one position to the left to fill the gap.
- The size of the list decreases by 1.
Because of the shifting of elements, the removal operation in ArrayList has a worst-case time complexity of O(n).
Example of removal by index:
ArrayList<String> list = new ArrayList<>();
list.add("A");
list.add("B");
list.add("C");
list.remove(1); // removes the element "B"
// Now list contains ["A", "C"]