ArrayList trimToSize() in Java with example

The trimToSize() method in Java trims the capacity of an ArrayList instance to be the list’s current size. This method is used to trim an ArrayList instance to the number of elements it contains.



Parameter: It does not accepts any parameter.

Return Value: It does not returns any value. It trims the capacity of this ArrayList instance to the number of the element it contains.

Errors and Exceptions: It does not have any errors and exceptions.

Below program illustrate the trimTosize() method:

// Java code to demonstrate the working of
// trimTosize() method in ArrayList

// for ArrayList functions
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);

        // using add(), add 5 values

        // trims the size to the number of elements

        System.out.println("The List elements are:");

        // prints all the elements
        for (Integer number : arr) {
            System.out.println("Number = " + number);


The List elements are:
Number = 2
Number = 4
Number = 5
Number = 6
Number = 11

I am weird, I am weirdo, u think u know me? Nah' ,u don't know me!

If you like GeeksforGeeks and would like to contribute, you can also write an article using or mail your article to See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Recommended Posts:

0 Average Difficulty : 0/5.0
No votes yet.