.trimToSize()
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 capacityArrayList<String> list = new ArrayList<>(10);// Add some elements to the listlist.add("Apple");list.add("Banana");list.add("Orange");// Trim the capacity to match the sizelist.trimToSize();System.out.println("Trimmed Capacity: " + list.size());}}
The output for the above code is:
Trimmed Capacity: 3
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.