How do I trim the capacity of an ArrayList?

For minimizing the storage used by an ArrayList to the number of it’s elements we can use the ArrayList.trimToSize() method call. In the code below we create an instance of ArrayList with the initial capacity set to 100. Later we only add five data into the list. To make the capacity of the ArrayList minimized we call the trimToSize() method.

package org.kodejava.example.util;

import java.util.ArrayList;

public class ListTrimToSize {
    public static void main(String[] args) {
        // Create an ArrayList with the initial capacity of 100.
        ArrayList list = new ArrayList(100);

        System.out.println("Size: " + list.size());
        // Trim the capacity of the ArrayList to the size
        // of the ArrayList. We can do this operation to reduce
        // the memory use to store data by the ArrayList.

Wayan Saryada

Programmer, runner, recreational diver, live in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, Hibernate / JPA.

Leave a Reply