.trimToSize()

Atreay's avatar
Published Dec 30, 2023
Contribute to Docs

The .trimToSize() method of the ArrayList class adjusts the capacity of the list to be the same as its size.

Syntax

The .trimToSize() method does not require any parameters. It adjusts the capacity of the ArrayList to be the same as its size:

list.trimToSize();

Example

The following example creates an ArrayList, uses .add() method to append elements to it, and then trims its capacity to match its size using .trimToSize():

import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
// Create an ArrayList of Strings with an initial capacity
ArrayList<String> list = new ArrayList<>(10);
// Add some elements to the list
list.add("Apple");
list.add("Banana");
list.add("Orange");
// Trim the capacity to match the size
list.trimToSize();
System.out.println("Trimmed Capacity: " + list.size());
}
}

The output for the above code is:

Trimmed Capacity: 3

All contributors

Contribute to Docs

Learn Java on Codecademy