Reduce the capacity of an ArrayList in java (trimToSize)

The method trimToSize() is used for memory optimization. It maintains the capacity of an ArrayList at the current list size. For example, an ArrayList has a capacity of 10 but contains only 5 items. By calling the method trimToSize(), the capacity will be reduced from 10 to 5.

In this example, we have defined an ArrayList with capacity 30. After adding 10 elements, we called the method trimToSize() which reduces the size of the list from 30 items to 10.

import java.util.ArrayList; 

public class ArrayList_Trim {

public static void main(String[] args) {
ArrayList< Integer> al = new ArrayList< Integer> ();
//minimum capacity of 50 elements
al.ensureCapacity(50);

al.add(1);
al.add(2);
al.add(3);
al.add(4);
al.add(5);
al.add(6);
al.add(7);
al.add(8);
al.add(9);
al.add(10);

al.trimToSize();

System.out.println(al.size());
for(Integer n:al)
System.out.println(n);
}
}
Runtime:

10
1
2
3
4
5
6
7
8
9
10