Flash cards
Review the key moves
What is the main idea behind Java ArrayList trimToSize() Method?
Lesson checks
Practice each idea before moving on
Short Mimo-style checks built from this lesson's code, terms, and sequence.
Which statement best captures the main point of this lesson?
Complete the missing token from the example code.
___ java.util.ArrayList;Put the learning moves in the order that makes the concept easiest to apply.
❮ ArrayList Methods
Example
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()