Java ArrayList trimToSize() Method
Example
Reduce the capacity of a list to exactly the size of the list:
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<String> cars = new ArrayList<String>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
cars.add("Mazda");
cars.trimToSize();
System.out.println(cars);
}
}
Definition and Usage
The trimToSize()
method reduces the capacity of a list to fit exactly the number of items that the list contains.
This method does not have a visible effect but it can can be used to reduce the memory usage of the list.
When an ArrayList
is created, capacity for 10 items is reserved unless another number is specified in the constructor. Even if the list does not have 10 items, this space is still reserved. Removing items from a list may leave the space for those items reserved. When you are not using of the capacity of an ArrayList
then there is some wasted memory which can accumulate if your program makes use of many ArrayList
s. You can use the trimToSize()
method to recover the unused memory.
Syntax
public void trimToSize()
Related Pages
❮ ArrayList Methods