English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Java Flow Control

Java Array

Java Object-Oriented (I)

Java Object-Oriented (II)

Java Object-Oriented (III)

Java Exception Handling

Java List

Java Queue (Queue)

Java Map Collection

Java Set Collection

Java Input Output (I/O)

Java Reader/Writer

Java other topics

Java ArrayList trimToSize() usage and example

Java ArrayList Methods

The Java ArrayList trimToSize() method trims (sets) the capacity of the arraylist to be equal to the number of elements in the arraylist.

The syntax of the trimToSize() method is:

arraylist.trimToSize();

trimToSize() parameters

trimToSize() method without any parameters

trimToSize() return value

The trimToSize() method does not return any value. Instead, it only changes the capacity of the arraylist.

Example1:Java ArrayList trimToSize()

import  java.util.ArrayList;
class  Main  {
    public  static  void  main(String[]  args)  {
        //Create  ArrayList
        ArrayList<String>  languages  =  new  ArrayList<>();
        //Add elements to  ArrayList
        languages.add("Java");
        languages.add("Python");
        languages.add("JavaScript");
        System.out.println("ArrayList:  ", + languages);
        // Trim capacity to 3
        languages.trimToSize();
        System.out.println("ArrayList size:  ", + languages.size());
    }
}

Output result

ArrayList:  [Java,  Python,  JavaScript]
ArrayList size: 3

In the above example, we created an ArrayList named languages. The arraylist contains3elements. Note this line,

languages.trimToSize();

Here, the trimToSize() method sets the capacity of the arraylist to be equal to languages (i.e.,3elements.)

We useArrayList size()method to get the number of elements in the arraylist.

NoteThe work of the ArrayList trimToSize() method is not visible.

What are the advantages of ArrayList trimToSize()?

We know that the capacity of ArrayList is dynamically changing. ThenWhat are the benefits of using the ArrayList trimToSize() method?

To understand the advantages of the trimToSize() method, we need to know the working principle of ArrayList.

Internally, ArrayList uses an array to store all its elements. Now, at some point, the array will be filled. When the internal array is full, a new array with the current array's capacity will be created.1.5times a new array. And, all elements are moved to the new array.

For example, if the internal array is full, we only need to add1elements. In this case, the ArrayList will expand at the same proportion (i.e., the previous array's1.5times).

In this case, there will be some unallocated space in the internal array. Therefore, the trimToSize() method will delete the unallocated space and change the capacity of the ArrayList to be equal to the number of elements in the ArrayList.

Java ArrayList Methods