Friday, September 5, 2025
HomeLanguagesJavaArrayList trimToSize() in Java with example

ArrayList trimToSize() in Java with example

The trimToSize() method of ArrayList in Java trims the capacity of an ArrayList instance to be the list’s current size. This method is used to trim an ArrayList instance to the number of elements it contains.

Syntax:

trimToSize()

Parameter: It does not accepts any parameter.

Return Value: It does not returns any value. It trims the capacity of this ArrayList instance to the number of the element it contains.

Errors and Exceptions: It does not have any errors and exceptions.

Below program illustrate the trimTosize() method:




// Java code to demonstrate the working of
// trimTosize() method in ArrayList
  
// for ArrayList functions
import java.util.ArrayList;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // creating an Empty Integer ArrayList
        ArrayList<Integer> arr = new ArrayList<Integer>(9);
  
        // using add(), add 5 values
        arr.add(2);
        arr.add(4);
        arr.add(5);
        arr.add(6);
        arr.add(11);
  
        // trims the size to the number of elements
        arr.trimToSize();
  
        System.out.println("The List elements are:");
  
        // prints all the elements
        for (Integer number : arr) {
            System.out.println("Number = " + number);
        }
    }
}


Output:

The List elements are:
Number = 2
Number = 4
Number = 5
Number = 6
Number = 11
Dominic
Dominichttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Dominic
32265 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6634 POSTS0 COMMENTS
Nicole Veronica
11801 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11863 POSTS0 COMMENTS
Shaida Kate Naidoo
6752 POSTS0 COMMENTS
Ted Musemwa
7025 POSTS0 COMMENTS
Thapelo Manthata
6703 POSTS0 COMMENTS
Umr Jansen
6718 POSTS0 COMMENTS