Sobes.tech
Junior — Middle

How does the capacity of ArrayList change after removing an element?

sobes.tech AI

Answer from AI

In the ArrayList class in Java, the capacity of the internal array does not automatically decrease after removing an element. The remove() method deletes the element and shifts subsequent elements to the left, but the size of the internal array (capacity) remains the same to avoid the overhead of frequent memory reallocation.

If you need to reduce the capacity, you can call the trimToSize() method, which reduces the capacity to the current size of the list.

Example:

ArrayList<String> list = new ArrayList<>(100); // capacity 100
list.add("A");
list.add("B");
list.remove(0); // capacity remains 100
list.trimToSize(); // capacity decreases to the current size (1)
How does the capacity of ArrayList change after… - sobes.tech