Curriculum
Course: Java Basic
Login

Curriculum

Java Basic

Java Home

0/1

Java Introduction

0/1

Java Get Started

0/1

Java Syntax

0/1

Java Comments

0/1

Java Type Casting

0/1

Java Operators

0/1

Java Booleans

0/1

Java Switch

0/1

Java Break / Continue

0/1

Java Errors and Exception

0/1
Text lesson

trimToSize()

Example

Shrink the capacity of a list to match its current size precisely.

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 adjusts the capacity of a list to exactly match the number of items it contains. While this method doesn’t have an immediate visible effect, it can be used to reduce the list’s memory usage.

When an ArrayList is created, it reserves capacity for 10 items by default unless a different number is specified in the constructor. Even if the list contains fewer than 10 items, this space remains reserved. Removing items from the list may still leave their space reserved. This can lead to wasted memory, especially if your program uses many ArrayLists. To reclaim this unused memory, you can use the trimToSize() method.

Syntax

public void trimToSize()