Java ArrayList trimToSize() Method Tutorial

In this section, we will learn what the ArrayList trimToSize() method is and how to use it in Java.

What is Java ArrayList trimToSize() Method?

An ArrayList object usually has more capacity than its current number of elements.

Capacity means the total number of elements that a list object can take. This capacity dynamically changes and by default it is designed to be higher than the current number of elements in a list.

But using Java ArrayList trimToSize() method, we can trim the capacity of a list and bring it down to be equal to the number of elements a list has.

This is mainly useful when we already stored a bunch of elements in a list and we know there won’t be any new element for the target list. So now by using this method we can release the unneeded space that a list has taken.

Java ArrayList trimToSize() Method Syntax:

public void trimToSize()

trimToSize() Method Parameters:

The method does not take an argument.

trimToSize() Method Return Value:

The method does not return a value.

trimToSize() Method Exceptions:

The method does not throw an exception.

Example: using ArrayList trimToSize() method

import java.util.List; 
import java.util.ArrayList; 

public class Main {

    public static void main(String[] args){
        List<Integer> list = new ArrayList<>();
        list.add(1);
        list.add(2);
        list.add(3);
        list.add(4);
        list.add(5);
        list.add(6);
        list.add(7);

       list.trimToSize();
    }
}

Leave a Reply