ArrayList trimToSize() Method in Java with Example
Last Updated : 10 Dec, 2024
Improve
In Java, the trimToSize() method is used to reduce the capacity of an ArrayList to match its current size. This helps to optimize memory usage when an ArrayList contains less elements than its allocated capacity.
Example 1: Here, we will use the trimToSize() method to trim an ArrayList of Strings.
// Java program to demonstrate the use of
// trimToSize() method in ArrayList of Strings
import java.util.ArrayList;
public class GFG {
public static void main(String[] args) {
// Creating an ArrayList of Strings
ArrayList<String> n = new ArrayList<>(10);
// Adding elements to the ArrayList
n.add("Ram");
n.add("Shyam");
n.add("Hari");
// print the size and
// capacity before trimming
System.out.println("Size before trim: " + n.size());
System.out.println("Capacity before trim: Excess capacity exists");
// Trimming to the size
// of the ArrayList
n.trimToSize();
// Printing the size after trimming
System.out.println("Size after trim: " + n.size());
}
}
Output
Size before trim: 3 Capacity before trim: Excess capacity exists Size after trim: 3
Syntax of trimToSize() Method
public void trimToSize()
Below is the diagram that represents the working of trimToSize() method of ArrayList.

Example 2: Here, we will use the trimToSize() method to trim an ArrayList of Integers.
// Java program to demonstrate trimToSize()
// with Integer ArrayList
import java.util.ArrayList;
public class GFG {
public static void main(String[] args) {
// creating an Empty Integer ArrayList
ArrayList<Integer> arr = new ArrayList<Integer>(9);
arr.add(2);
arr.add(4);
arr.add(5);
arr.add(6);
arr.add(11);
// trims the size to the
// number of elements
arr.trimToSize();
System.out.println("The List elements are:");
// prints all the elements
for (Integer n : arr) {
System.out.println("Number:" + n);
}
}
}
Output
The List elements are: Number:2 Number:4 Number:5 Number:6 Number:11
Example 3: Here, we will check the behavior of trimToSize() on an empty ArrayList.
// Java program to show trimToSize()
// on an empty ArrayList
import java.util.ArrayList;
public class GFG {
public static void main(String[] args) {
// Creating an empty ArrayList
ArrayList<String> arr = new ArrayList<>();
// Trimming the capacity of
// an empty ArrayList
arr.trimToSize();
// Printing the size after trimming
System.out.println("Size of empty ArrayList after trim: " + arr.size());
}
}
Output
Size of empty ArrayList after trim: 0