Easy Tutorial
❮ Collection Hashtable Key Java Networking ❯

Java ArrayList trimToSize() Method

Java ArrayList

The trimToSize() method is used to adjust the capacity of the dynamic array to the number of elements in the array.

The syntax for the trimToSize() method is:

arraylist.trimToSize();

Note: arraylist is an object of the ArrayList class.

Parameters:

Return Value

There is no return value; it only changes the capacity of the arraylist.

Example

The following example demonstrates the use of the trimToSize() method:

Example

import java.util.ArrayList;

class Main {
    public static void main(String[] args){

        // Create a dynamic array
        ArrayList<String> sites = new ArrayList<>();

        sites.add("Google");
        sites.add("tutorialpro");
        sites.add("Taobao");

        System.out.println("ArrayList : " + sites);

        // Adjust capacity to 3
        sites.trimToSize();
        System.out.println("ArrayList size: " + sites.size());
    }
}

Executing the above program outputs:

ArrayList : [Google, tutorialpro, Taobao]
ArrayList size: 3

In the above example, the trimToSize() method sets the capacity of the dynamic array to the number of elements in sites (which is 3).

Advantages of ArrayList trimToSize()

We know that the capacity of an ArrayList is dynamically adjustable. What are the benefits of using the trimToSize() method?

To understand the advantages of the trimToSize() method, we need to look into how ArrayList works internally.

Internally, ArrayList uses an array to store elements. When the array is about to be full, a new array with a capacity of 1.5 times the current array is created.

Also, all elements are moved to the new array. Suppose the internal array is full, and we add one more element; the ArrayList capacity will expand by the same ratio (1.5 times the previous array).

In this case, there will be some unallocated space in the internal array.

Here, the trimToSize() method can remove the unallocated space and change the capacity of the ArrayList to match the number of elements in the ArrayList.

Java ArrayList

❮ Collection Hashtable Key Java Networking ❯