coderolls Staff
coderolls Staff Hi 👋🏼, At coderolls we write tutorials about Java programming language and related technologies.

ArrayList trimToSize() method

In this tutorial, we will see the trimToSize() method of the ArrayList class in Java.

Introduction

In the last few tutorials, we are looking at various methods of the ArrayList class in Java.

We have seen a few methods of the ArrayList class before like add(), addAll(), remove(), set(), iterate(), clear(), contains(), get(), removeRange(), retainAll() and subList() method.

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 trimToSize() method.

This method trims the capacity of this ArrayList instance to be the list’s current size.

ArrayList trimToSize() method

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 blocks in the memory to store the arraylist elements. So, if we add the 10 elements to the arrayList, 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.

1
states.trimToSize();

So, if there are only two elements 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 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.

Conclusion

The 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 Newsletter
Get the latest tutorials right in your inbox. We never spam!

comments powered by Disqus