If you want to efficiently remove several adjacent elements from the middle of an ArrayList
, there’s a much better way than calling remove(index)
in a loop.
Let’s go step by step 👇
❌ Inefficient way (common mistake):
for (int i = 0; i < count; i++) {
list.remove(startIndex); // each remove() causes a shift!
}
This is O(n × k) time, where:
n
is the size of the listk
is the number of elements being removed
Because each call to remove()
shifts elements left one-by-one.
✅ Efficient way: Use subList().clear()
list.subList(startIndex, endIndex).clear();
Removes all elements in one bulk operation
Time complexity: O(n – endIndex) – shifts remaining tail only once
List<String> list = new ArrayList<>(
Arrays.asList("A", "B", "C", "D", "E", "F", "G")
);
// Remove 3 elements from index 2 (i.e., "C", "D", "E")
int start = 2;
int count = 3;
list.subList(start, start + count).clear();
System.out.println(list); // [A, B, F, G]
🧠 Why is this efficient?
subList()
gives you a view of part of the list.clear()
on the view:- Removes all elements in one go.
- Shifts tail elements only once.
- No multiple reallocations or shifting.
🚀 Summary:
Method | Time Complexity | Efficiency |
---|---|---|
Loop with remove(index) | ❌ O(n × k) | Slow |
subList(start, end).clear() | ✅ O(n – end) | Fast |