The syntax of the
trimToSize() method is:
Here, arraylist is an object of the
trimToSize() method does not take any parameters
trimToSize() Return Value
trimToSize() method does not return any value. Rather, it only changes the capacity of the arraylist.
Example 1: Java ArrayList trimToSize()
In the above example, we have created two arraylists named languages. The arraylist contains 3 elements. Notice the line,
trimToSize() method sets the capacity of arraylist equal to the number of elements in languages (i.e. 3).
We have used the ArrayList size() method to get the number of elements in the arraylist.
Advantage of ArrayList trimToSize()
We know that the capacity of
ArrayList is dynamically changed. So what is the advantage of using ArrayList trimToSize() method?
To understand the advantage of
trimToSize() method, we need to look into the working of
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 is created with 1.5 times more capacity than the current array. And, all elements are moved to the new array.
For example, suppose the internal array is full and we have to add only 1 element. Here, the
ArrayList will expand with the same ratio (i.e. 1.5 times the previous array).
In this case, there will be some unassigned space in the internal array. Hence, the
trimToSize() method removes the unassigned space and changes the capacity of arraylist equal to the number of elements in the arraylist.
This working of ArrayList
trimToSize() method is not visible to the user.