Java ArrayList.trimToSize() Method

 Posted On  | Yashwant Chavan 

In this tutorial you will learn about ArrayList.trimToSize() method. It 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.


ArrayList will be trimmed to its current size. Which helps to minimize the storage of an ArrayList instance.

void java.util.ArrayList.trimToSize();


returns void

Java ArrayList.trimToSize() example

Refer below steps

  • Constructs an empty ArrayList with an initial capacity of 5 elements using new ArrayList<String>().
  • Add some elements in colors ArrayList using add() method.
  • Print the size of ArrayList before and after calling trimToSize() method.
  • Here you will not get the difference, because both the output values are same, To get the better understanding of how ArrayList.trimToSize() method works, refer below screen shots.
  • I have executed below program in debug mode. In first screen shot you will see, ArrayList allocated 5 elements.
  • In second screen shot, You will notice that ArrayList is trimmed to its current size as 3.

import java.util.ArrayList;

public class ArrayListTrimToSize {
    public static void main(String[] args) {

        ArrayList <String> colors = new ArrayList <String> (5);
        System.out.println("Before trimToSize() ? :- " + colors.size());
        System.out.println("After trimToSize() ? :- " + colors.size());



Before trimToSize() ? :- 3
After trimToSize() ? :- 3

Before trimToSize()

ArrayList before trimToSize()

After trimToSize()

ArrayList after trimToSize()

© 2018

 |  Find us on Google+ |  Rss Feed

Loaded in 0.0491 seconds.