Step 3 of 6
50% CompleteRemove Operation
Learn how to remove elements from an ArrayList
The Remove Operation
The remove operation deletes an element from an ArrayList. This requires shifting remaining elements to fill the gap left by the removed element.
When removing an element, the ArrayList performs:
- Finding the element to be removed
- Shifting all elements after it one position to the left
- Decreasing the size counter
- Optionally shrinking capacity if size becomes too small
Removing by Index
Remove an element at a specific index. Time complexity depends on position: - Remove at end: O(1) - Remove at middle: O(n) - Remove at beginning: O(n)
Array Visualization
Size: 5 | Capacity: 10
ArrayList<Integer> list = new ArrayList<>();list.add(10); // [10]list.add(20); // [10, 20]list.add(30); // [10, 20, 30]list.add(40); // [10, 20, 30, 40]// Remove element at index 1 (value 20)list.remove(1); // [10, 30, 40]// Elements after index 1 shift left: 30 moves to index 1, 40 moves to index 2
Removing by Value
Remove the first occurrence of a specific value. The ArrayList searches for the value and removes it if found. Time complexity: O(n) for searching and shifting.
ArrayList<String> list = new ArrayList<>();list.add("Apple");list.add("Banana");list.add("Cherry");list.add("Banana");// Remove first occurrence of "Banana"list.remove("Banana"); // [Apple, Cherry, Banana]// Only the FIRST occurrence is removed// The second "Banana" remains in the list
Removing Multiple Elements
When removing multiple elements, be careful with indices as they change after each removal.
ArrayList<Integer> list = new ArrayList<>();for (int i = 1; i <= 5; i++) {list.add(i * 10);}// [10, 20, 30, 40, 50]// WRONG: Don't use forward iterationfor (int i = 0; i < list.size(); i++) {if (list.get(i) > 20) {list.remove(i); // BUG: Skips elements!}}// CORRECT: Use backward iterationfor (int i = list.size() - 1; i >= 0; i--) {if (list.get(i) > 20) {list.remove(i); // Removes 30, 40, 50}}// Result: [10, 20]
Tip: When removing multiple elements, iterate backwards to avoid skipping elements or use an iterator with the remove() method.
Clear All Elements
Remove all elements from the ArrayList. Time complexity: O(n) to clear all references.
ArrayList<Integer> list = new ArrayList<>();list.add(10);list.add(20);list.add(30);// [10, 20, 30], size: 3, capacity: varies// Clear all elementslist.clear();// [], size: 0, capacity: unchanged// The internal array capacity may remain the same to avoid reallocation
Practice Exercise
Key Takeaways
- Remove by index: O(1) at end, O(n) at beginning/middle
- Remove by value: O(n) to find and shift elements
- Multiple removals: Iterate backwards to avoid index issues
- Clear: O(n) time to remove all elements