Java.Collections.How are elements removed from an ArrayList? How does the size of the ArrayList change in this case?

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:

  1. Checks bounds to make sure index is valid.
  2. Removes the element at that index.
  3. Shifts all subsequent elements one position to the left to fill the gap.
  4. Sets the now-unused last array element to null to prevent memory leaks (called loitering).
  5. Decrements size by 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:

OperationTime
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 size shrinks, but the internal array remains the same length.
  • You can shrink it manually using:
list.trimToSize();

✅ Summary:

ActionWhat happens
remove(index)Shifts right-side elements left
sizeDecreases by 1
capacity (internal)Stays the same
Memory leak?Prevented (last element set to null)
This entry was posted in Без рубрики. Bookmark the permalink.