English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
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() method without any parameters
The trimToSize() method does not return any value. Instead, it only changes the capacity of the arraylist.
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.
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.