bugl
bugl
HomeLearnPatternsPathsSearch
HomeLearnPatternsPathsSearch

Loading lesson path

Learn/Java/Java Reference
Java•Java Reference

Java ArrayList trimToSize() Method

Flash cards

Review the key moves

1/4
Core idea

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.

1Quick choice

Which statement best captures the main point of this lesson?

2Fill blank

Complete the missing token from the example code.

___ java.util.ArrayList;
3Order

Put the learning moves in the order that makes the concept easiest to apply.

The trimToSize() method reduces the capacity of a list to fit exactly the number of items that the list contains.
Definition and Usage
Java ArrayList trimToSize() Method

❮ 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()

Previous

Java ArrayList toArray() Method

Next

Java LinkedList Methods