Java ArrayList - trimToSize() Method
The java.util.ArrayList.trimToSize() method is used to trim the capacity of the given ArrayList to be the list's current size. An application can use this operation to minimize the storage of an ArrayList instance.
Syntax
public void trimToSize()
Parameters
No parameter is required.
Return Value
void type.
Exception
NA.
Example:
In the example below, the java.util.ArrayList.trimToSize() method is used to trim the capacity of the given ArrayList to be the list's current size.
import java.util.*; public class MyClass { public static void main(String[] args) { //creating an ArrayList with capacity 10 ArrayList<Integer> MyList = new ArrayList<Integer>(10); //populating the ArrayList MyList.add(10); MyList.add(20); MyList.add(30); MyList.add(40); //trim the capacity of the ArrayList to 4 MyList.trimToSize(); //print the content the ArrayList System.out.println("MyList contains: "+ MyList); } }
The output of the above code will be:
MyList contains: [10, 20, 30, 40]
❮ Java.util - ArrayList