Java ArrayList trimToSize() Method
The trimToSize() method is used to adjust the capacity of the dynamic array to the number of elements in the array.
The syntax of the trimToSize() method is:
arraylist.trimToSize();
Note:arraylist is an object of the ArrayList class.
Parameter Description:
- None
Return Value
No return value, only changes the capacity of the arraylist.
Example
The following example demonstrates the use of the trimToSize() method:
Example
class Main {
public static void main(String[] args){
// Create a dynamic array
ArrayList<String> sites = new ArrayList<>();
sites.add("Google");
sites.add("Example");
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 produces the following output:
ArrayList : [Google, Example, Taobao] ArrayList 大小: 3
In the above example, the trimToSize() method sets the capacity of the dynamic array to the number of elements in sites (i.e., 3).
Advantages of ArrayList trimToSize()
We know that the capacity of ArrayList changes dynamically. So what is the benefit of using the ArrayList trimToSize() method?
To understand the advantages of the trimToSize() method, we need to study the internal working principles of ArrayList.
ArrayList internally uses an array to store elements. When the array is about to be full, a new array is created with a capacity 1.5 times that of the current array.
At the same time, all elements are moved to the new array. Suppose the internal array is full and we add 1 more element, the ArrayList capacity will expand by the same ratio (i.e., 1.5 times the previous array).
In this case, there will be some unallocated space in the internal array.
At this point, the trimToSize() method can remove the unallocated space and change the capacity of the ArrayList to equal the number of elements in the ArrayList.
Other Extensions
Java ArrayList