Java .trimToSize()

Atreay's avatar
Published Dec 30, 2023

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

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn to code in Java — a robust programming language used to create software, web and mobile apps, and more.
    • Beginner Friendly.
      17 hours

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

Learn Java on Codecademy

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn to code in Java — a robust programming language used to create software, web and mobile apps, and more.
    • Beginner Friendly.
      17 hours