trimToSize()
method is used for memory optimization. It trims the capacity of ArrayList
to the current list size. For e.g. An arraylist is having capacity of 15 but there are only 5 elements in it, calling trimToSize() method on this ArrayList would change the capacity from 15 to 5.
public void trimToSize()
Example
Here I have defined the ArrayList of capacity 50. After adding 10 elements I called trimToSize() method which would have reduced the capacity from 50 to 10 (current size of arraylist).
package beginnersbook.com; import java.util.ArrayList; public class TrimExample { public static void main(String args[]) { ArrayList<Integer> arraylist = new ArrayList<Integer>(50); arraylist.add(1); arraylist.add(2); arraylist.add(3); arraylist.add(4); arraylist.add(5); arraylist.add(6); arraylist.add(7); arraylist.add(1); arraylist.add(1); arraylist.add(1); arraylist.trimToSize(); System.out.println(arraylist); } }
Output:
[1, 2, 3, 4, 5, 6, 7, 1, 1, 1]
Lathy says
Hi,
I ran your code. It prints the same result whether trimToSize() method added or removed.
I even checked the size of the arraylist with and without trimToSize() method but in both case it remains same.
Can you please check and update.
Tony says
@Lathy, There is a difference between size and capacity of an ArrayList. Size is the number of data items stored in an ArrayList. Capacity is the length of the Array that is used internally by the ArrayList. For obvious reasons, Capacity is always maintained greater than or equal to the Size. The trimToSize() method is used in situations where you know the ArrayList size is not likely to increase and you do not want to waste more memory space. Look up the implementation of ArrayList for more info.
Sudarshan says
Good Day Guys,
Can we restrict the size of the Arraylist ?
eg : I should add only 10 objects to the arraylist.
Chaitanya Singh says
Hey Sudarshan, You cannot restrict the size of an ArrayList. Why you want to do that? You could have used array instead of ArrayList if you want the size to be limited.
However if you want to achieve this in ArrayList then you have to limit the size by yourself in the code, something like this would work: