For minimizing the storage used by an ArrayList
to the number of its elements we can use the ArrayList.trimToSize()
method call. In the code below we create an instance of ArrayList
with the initial capacity set to 100. Later we only add five data into the list. To make the capacity of the ArrayList
minimized we call the trimToSize()
method.
package org.kodejava.util;
import java.util.ArrayList;
public class ListTrimToSize {
public static void main(String[] args) {
// Create an ArrayList with the initial capacity of 100.
ArrayList<String> list = new ArrayList<>(100);
list.add("A");
list.add("B");
list.add("C");
list.add("D");
list.add("E");
list.add("F");
System.out.println("Size: " + list.size());
// Trim the capacity of the ArrayList to the size
// of the ArrayList. We can do this operation to reduce
// the memory used to store data by the ArrayList.
list.trimToSize();
}
}
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024