Let’s break down exactly how elements are removed from an ArrayList, and how that affects its size and internal structure.
🔧 How does removal work?
🔹 When you do:
list.remove(index);
Java does the following under the hood:
- Checks bounds to make sure
indexis valid. - Removes the element at that index.
- Shifts all subsequent elements one position to the left to fill the gap.
- Sets the now-unused last array element to
nullto prevent memory leaks (called loitering). - Decrements
sizeby 1.
🧠 Example:
ArrayList<String> list = new ArrayList<>();
list.add("A");
list.add("B");
list.add("C");
list.remove(1); // removes "B"
Result:
list = ["A", "C"]
size = 2
Behind the scenes:
- “C” is shifted left to fill position 1.
- The last slot is nulled.
- Size is now 2.
📦 What about remove(object)?
list.remove("C");
- It searches linearly using
.equals(). - Removes the first matching element.
- Then shifts elements left, same as above.
- Size still decreases by 1.
⏱️ Time complexity:
| Operation | Time |
|---|---|
remove(index) | ❌ O(n) (worst case, due to shifting) |
remove(object) | ❌ O(n) (search + shifting) |
🔄 Does capacity shrink?
❌ No, removing elements does not reduce the internal array capacity.
- The
sizeshrinks, but the internal array remains the same length. - You can shrink it manually using:
list.trimToSize();
✅ Summary:
| Action | What happens |
|---|---|
remove(index) | Shifts right-side elements left |
size | Decreases by 1 |
capacity (internal) | Stays the same |
| Memory leak? | Prevented (last element set to null) |