The ArrayList.trimToSize() method minimizes the memory footprint of an ArrayList instance by shrinking its internal Object[] backing array capacity down to match the list's current logical ArrayList.size().
Why Manual Trimming Exists: Although ArrayList automatically grows its backing array during add() or ensureCapacity(), it never shrinks automatically after remove(), removeAll(), or clear(). Calling trimToSize() releases those unused trailing array slots back to the JVM heap.
Declared on java.util.ArrayList<E> (not part of the List interface):
// Trims the capacity of this ArrayList instance to be the list's current size()
public void trimToSize()
| Aspect | Specification | Internal Behavior |
|---|---|---|
| Return Type | void |
Reallocates elementData in place via Arrays.copyOf(elementData, size). |
When size == 0 |
Zero allocation | Replaces elementData with the shared static EMPTY_ELEMENTDATA ({}) array. |
| Time Complexity | O(n) |
Copies the n = size() active references into a newly allocated array of length n. |
If an ArrayList was initialized with capacity 50 but only 6 elements were added via add(), 44 array slots sit unused in memory. Calling marks.trimToSize() shrinks the internal buffer to length 6:
import java.util.ArrayList;
ArrayList<Integer> marks = new ArrayList<Integer>(50); // Allocates Object[50]
marks.add(54);
marks.add(55);
marks.add(56);
marks.add(57);
marks.add(58);
marks.add(59);
// Shrinks internal Object[50] down to exact Object[6] (44 unused slots freed!)
marks.trimToSize();
System.out.println(marks); // [54, 55, 56, 57, 58, 59]Terminal Output:
[54, 55, 56, 57, 58, 59]
No! A common misconception is that trimToSize() alters size(). In fact, trimToSize() shrinks the hidden capacity to match size(); the logical element count and elements themselves remain 100% unchanged:
ArrayList<String> langs = new ArrayList<>(100);
langs.add("Java");
langs.add("PHP");
System.out.println("size() before trimToSize(): " + langs.size()); // 2
langs.trimToSize();
System.out.println("size() after trimToSize(): " + langs.size()); // Still 2!Terminal Output:
size() before trimToSize(): 2
size() after trimToSize(): 2
When you call clear() on a list that held 10,000 elements, the element references are nulled out, but the Object[10000] array itself stays allocated inside the list. Calling trimToSize() immediately after clear() releases that 10,000-slot array for garbage collection:
ArrayList<Integer> spike = new ArrayList<>(10000);
for (int i = 0; i < 8000; i++) spike.add(i);
spike.clear(); // Logical size is 0, but Object[10000] buffer is still held!
spike.trimToSize(); // Replaces Object[10000] with shared 0-length EMPTY_ELEMENTDATA
System.out.println("After clear + trimToSize -> isEmpty: " + spike.isEmpty());Terminal Output:
After clear + trimToSize -> isEmpty: true
The list remains completely mutable after trimToSize(). However, because there are zero spare slots left in the backing array, the very next call to add() will trigger a 1.5x array growth reallocation:
ArrayList<String> items = new ArrayList<>(20);
items.add("A");
items.add("B");
items.trimToSize(); // Backing array is now exact length 2
// Adding a 3rd item forces an immediate 1.5x array resize (length 2 -> 3)
items.add("C");
System.out.println("Expanded again after add: " + items);Terminal Output:
Expanded again after add: [A, B, C]
How trimToSize() pairs with other capacity and lifecycle methods:
| Method | Effect on Capacity | Effect on Logical size() |
|---|---|---|
list.trimToSize() |
Shrinks to exact size() |
Unchanged |
list.ensureCapacity(n) |
Grows to at least n |
Unchanged |
list.clear() |
Unchanged (retains buffer) | Resets to 0 |
list.clone() |
New list has capacity == size() |
Same as original |
When building an in-memory lookup table where the exact number of surviving items is unknown ahead of time, over-allocate during ingestion and call trimToSize() once before publishing the cache:
public class CompactReadOnlyCache {
public static ArrayList<Integer> buildPrimeCache(int limit) {
ArrayList<Integer> primes = new ArrayList<>(limit); // Over-allocate upfront
for (int n = 2; n <= limit; n++) {
boolean isPrime = true;
for (int d = 2; d * d <= n; d++) if (n % d == 0) { isPrime = false; break; }
if (isPrime) primes.add(n);
}
primes.trimToSize(); // Compact once before returning long-lived cache!
return primes;
}
public static void main(String[] args) {
System.out.println("Primes <= 15: " + buildPrimeCache(15));
}
}Terminal Output:
Primes <= 15: [2, 3, 5, 7, 11, 13]
In a graph or bucketed table with thousands of inner ArrayList rows, default 10-slot capacities waste significant memory when most rows hold only 1 or 2 items. Trim each inner list as well as the outer list:
public class Compact2DBuckets {
public static void main(String[] args) {
ArrayList<ArrayList<String>> buckets = new ArrayList<>(10);
for (int i = 0; i < 2; i++) {
ArrayList<String> row = new ArrayList<>(50);
row.add("Item-" + i);
row.trimToSize(); // Trim each inner list
buckets.add(row);
}
buckets.trimToSize(); // Trim outer list
System.out.println("Compacted 2D buckets: " + buckets);
}
}Terminal Output:
Compacted 2D buckets: [[Item-0], [Item-1]]
Never call trimToSize() on every iteration of a loop that adds or removes elements! Doing so forces a full O(n) array copy on every step, degrading amortized O(1) appends into O(n^2) CPU thrashing. Call trimToSize() only once after the loop finishes.
Even though trimToSize() does not change the logical elements, OpenJDK increments modCount unconditionally inside trimToSize(). Calling it while an Iterator or ListIterator is open will trigger a ConcurrentModificationException on the next iterator step.
Compile and run this verification class in any Java environment:
public class ArrayListTrimToSizeFullDemo {
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<>(100);
list.addAll(Arrays.asList(10, 20, 30));
list.trimToSize();
if (list.size() == 3 && list.get(2) == 30) {
System.out.println("Check 1 Passed: Elements and size() preserved after trimToSize().");
}
list.clear();
list.trimToSize();
if (list.isEmpty()) {
System.out.println("Check 2 Passed: Empty list trimmed to zero capacity.");
}
System.out.println("All ArrayList.trimToSize() verification checks passed!");
}
}Terminal Output:
Check 1 Passed: Elements and size() preserved after trimToSize().
Check 2 Passed: Empty list trimmed to zero capacity.
All ArrayList.trimToSize() verification checks passed!
The internal check if (size < elementData.length) evaluates to false, so trimToSize() does not reallocate or copy the array.
Automatic shrinking on remove() can cause "oscillation thrashing" if a list repeatedly adds and removes elements near a threshold, and many lists are short-lived local variables that are garbage-collected as a whole anyway.
Because trimToSize() is specific to ArrayList (not part of the java.util.List interface). Either declare the variable as ArrayList<String> or check if (list instanceof ArrayList) ((ArrayList<?>) list).trimToSize();.
Yes. Both new ArrayList<>(existingList) and existingList.clone() allocate the new list's backing array to the exact existingList.size().
trimToSize().ArrayList.ArrayList.ArrayList methods.Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.