Course contentsShow
← Java
Lesson 1009 of 2,87024. List ImplementationsFree lesson

trimToSize: Reclaiming Unused Capacity

Discover how to shrink the backing array to exactly match the current size and free memory.

trimToSize: Reclaiming Unused Capacity

You'll learn how to shrink an ArrayList's internal array to match its actual size and free up wasted memory.

The Memory Gap Problem

You already know that an ArrayList's capacity (the size of its backing array) is often larger than its size (the number of elements it actually holds). After adding many elements, then removing some, or after constructing with a large initial capacity but only adding a few items, you end up with a lot of unused space in the backing array. That unused space still consumes memory.

What trimToSize Does

The trimToSize() method shrinks the internal array to exactly match the current number of elements. Think of it like vacuum-sealing a bag of clothes—you're squeezing out all the empty space to minimize storage.

When you call trimToSize(), ArrayList creates a new array with length equal to size, copies all elements over using System.arraycopy, and replaces the old backing array. The unused capacity disappears, and the memory can be reclaimed by the garbage collector.

When to Use It

Call trimToSize() when:

  • You've finished building a list and won't add more elements
  • You've removed many elements and want to reclaim memory
  • You're holding the list long-term and memory efficiency matters

Trade-off: If you call trimToSize() and then add elements again, you'll immediately trigger array growth, which is expensive. Only trim when you're confident the list size is stable.

ArrayList<String> names = new ArrayList<>(100);
names.add("Alice");
names.add("Bob");
// capacity = 100, size = 2 (98 wasted slots!)

names.trimToSize();
// capacity = 2, size = 2 (no waste)

Key Takeaway: Use trimToSize() to eliminate wasted capacity in an ArrayList's backing array and reclaim memory when the list size is stable.