ArrayList trimToSize() Method in Java with Example
In Java, an ArrayList has a dynamic internal array to store elements. Sometimes, the allocated array is larger than the actual number of elements. This extra capacity consumes memory unnecessarily. The trimToSize() method of ArrayList reduces its capacity to match its current size, optimizing memory usage.
- size(): Number of elements currently in the list.
- capacity: Total space allocated internally.
- trimToSize(): does not change the size, only reduces unused internal capacity.
Example 1: Trimming a String ArrayList
import java.util.ArrayList;
public class GFG{
public static void main(String[] args)
{
ArrayList<String> names
= new ArrayList<>(10); // initial capacity 10
names.add("Ram");
names.add("Shyam");
names.add("Hari");
System.out.println("Size before trim: "
+ names.size());
System.out.println(
"Note: internal capacity > size before trim");
// Trimming the capacity
names.trimToSize();
System.out.println("Size after trim: "
+ names.size());
System.out.println(
"Capacity now matches size internally");
}
}
Output
Size before trim: 3 Note: internal capacity > size before trim Size after trim: 3 Capacity now matches size internally
Syntax:
public void trimToSize()
Below is the diagram that represents the working of trimToSize() method of ArrayList.

Example 2: Trimming an Integer ArrayList
import java.util.ArrayList;
public class GFG{
public static void main(String[] args)
{
ArrayList<Integer> numbers
= new ArrayList<>(8); // initial capacity 8
numbers.add(2);
numbers.add(4);
numbers.add(5);
numbers.add(6);
numbers.add(11);
System.out.println("ArrayList elements: "
+ numbers);
// trim the capacity to match the number of elements
numbers.trimToSize();
System.out.println("Size after trim: "
+ numbers.size());
System.out.println(
"Internal capacity now matches number of elements");
}
}
Output
ArrayList elements: [2, 4, 5, 6, 11] Size after trim: 5 Internal capacity now matches number of elements
Example 3: Trimming an Empty ArrayList
import java.util.ArrayList;
public class GFG{
public static void main(String[] args){
ArrayList<String> emptyList = new ArrayList<>();
System.out.println("Size before trim: " + emptyList.size());
emptyList.trimToSize(); // trims capacity to 0
System.out.println("Size after trim: " + emptyList.size());
}
}
Output
Size before trim: 0 Size after trim: 0