ArrayList trimToSize() method
In this tutorial, we will see the
trimToSize() method of the ArrayList class in Java.
In last few tutorials, we are looking at various methods of the ArrayList class in Java.
ArrayList is a widely used class to store and retrieve data in a collection framework.
ArrayList is an ordered collection i.e. it maintains the insertion order of the elements. Also, it allows duplicate elements in the list.
Today we will see the
This method trims the capacity of this ArrayList instance to be the list’s current size.
When we create a new ArrayList instance, it will get created with the default initial capacity of 10.
1 List<String> states = new ArrayList<String>();
That means it reserves the 10 block in the memory to store the
arraylist elements. So , if we add the 10 elements to the
arrayList can potentially accommodate without reallocating its internal structures.
But, if we just added two elements to the
arrayList, the remaining blocks will remain empty and not used.
1 2 states.add("California"); states.add("Texas");
Here, we can use the
trimToSize() method to trim the capacity of this
arrayList instance to be the list’s current size.
So, if there are only two elements got added to the list and we invoke
trimToSize() on it, the capacity will be two only. It frees the remaining reserved blocks from the memory.
The method is signature is given below.
1 public void trimToSize()
This method does not accept any parameter and has a return type as a
void i.e. it do not return anything.
Also, no exception occurs while invoking this method.
trimToSize() method trims the capacity of this ArrayList instance to be the list’s current size.
Please write your thoughts in the comment section below.
Join NewsletterGet the latest tutorials right in your inbox. We never spam!