Java ArrayList trimToSize()

The Java ArrayList trimToSize() method trims (sets) the capacity of the arraylist equal to the number of elements in the arraylist.

The syntax of the trimToSize() method is:

arraylist.trimToSize();

Here, arraylist is an object of the ArrayList class.


trimToSize() Parameters

The trimToSize() method does not take any parameters


trimToSize() Return Value

The trimToSize() method does not return any value. Rather, it only changes the capacity of the arraylist.


Example 1: Java ArrayList trimToSize()

import java.util.ArrayList;

class Main {
    public static void main(String[] args) {
        // create an ArrayList
        ArrayList<String> languages = new ArrayList<>();

        // add element to ArrayList
        languages.add("Java");
        languages.add("Python");
        languages.add("JavaScript");
        System.out.println("ArrayList: " + languages);

        // trim capacity to 3
        languages.trimToSize();
        System.out.println("Size of ArrayList: " + languages.size());
    }
}

Output

ArrayList: [Java, Python, JavaScript]
Size of ArrayList: 3

In the above example, we have created two arraylists named languages. The arraylist contains 3 elements. Notice the line,

languages.trimToSize();

Here, the trimToSize() method sets the capacity of arraylist equal to the number of elements in languages (i.e. 3).

We have used the ArrayList size() method to get the number of elements in the arraylist.


Advantage of ArrayList trimToSize()

We know that the capacity of ArrayList is dynamically changed. So what is the advantage of using ArrayList trimToSize() method?

To understand the advantage of trimToSize() method, we need to look into the working of ArrayList.

Internally, ArrayList uses an array to store all its elements. Now, at some point, the array will be filled. When the internal array is full, a new array is created with 1.5 times more capacity than the current array. And, all elements are moved to the new array.

For example, suppose the internal array is full and we have to add only 1 element. Here, the ArrayList will expand with the same ratio (i.e. 1.5 times the previous array).

In this case, there will be some unassigned space in the internal array. Hence, the trimToSize() method removes the unassigned space and changes the capacity of arraylist equal to the number of elements in the arraylist.

This working of ArrayList trimToSize() method is not visible to the user.