Java ArrayList trimToSize() Method Example

The trimToSize() method of java.util.ArrayList class trims the capacity of this ArrayList instance to be the list’s current size. An application can use this operation to minimize the storage of an ArrayList instance.

Signature

public void trimToSize()

This method trims the capacity of this ArrayList instance to be the list’s current size.

Example

The following example shows the usage of java.util.Arraylist.trimToSize() method.

import java.util.ArrayList;

public class TrimToSizeArrayListExample 
{
    public static void main(String args[])
    {
        ArrayList<String> al1 = new ArrayList<String>();
        
        //Adding elements to al1
        al1.add("one");
        al1.add("two");
        al1.add("three");
        al1.add("four");

        //Triming the arraylist al1
        al1.trimToSize();
        
        //Print the elements of al1
        System.out.println("**Elements of al1**");
        for(String val : al1)
        {
            System.out.println(val);
        }
    }
}

Output

**Elements of al1**
one
two
three
four

Leave a Reply

Your email address will not be published. Required fields are marked *