Yandex

Java Advanced ConceptsJava Advanced Concepts3

Java ArrayList trimToSize() method
Syntax and Examples


Introduction

Sometimes, you might notice that your `ArrayList` uses more memory than it strictly needs. This happens because an `ArrayList` automatically increases its internal capacity to accommodate new elements. However, if the actual number of elements is significantly less than this allocated capacity, you can reclaim some memory using the trimToSize() method.

The trimToSize() method doesn't reduce the size of your list (the number of elements it contains). It simply reduces the capacity of the underlying array. Think of it like this: imagine you have a bookshelf with space for 100 books, but currently only 50 are on it. `trimToSize()` is akin to making the bookshelf smaller so that it only has room for 75 books – no books disappear from the shelf; the bookshelf just becomes more efficient in its use of space.

Syntax

public void trimToSize()

Parameters

Parameter Description
None This method does not accept any parameters.

Return Value

The trimToSize() method returns nothing (void).

Examples

Example 1: Trimming an ArrayList after adding many elements

This example demonstrates how `trimToSize()` can be used to reduce the memory footprint of an `ArrayList` after you've added a large number of elements, but then realize that only a fraction are actually needed.

import java.util.ArrayList;

public class TrimToSizeExample {
    public static void main(String[] args) {
        // Create an ArrayList with initial capacity of 10
        ArrayList<Integer> list = new ArrayList<>(10);

        // Add many elements - this will likely increase the internal capacity 
        for (int i = 0; i < 20; i++) {
            list.add(i);
        }

        System.out.println("Size: " + list.size()); // Output: Size: 20
        System.out.println("Capacity: " + list.capacity());  // Print the capacity to see how much it increased.

        // Remove most of the elements
        list.remove(5); //Removes element at index 5
        list.remove(7); //Removes element at index 7
        list.remove(9);  //Removes element at index 9
        list.remove(11); //Removes element at index 11
        list.remove(13); //Removes element at index 13
        list.remove(15); //Removes element at index 15
        list.remove(17); //Removes element at index 17
        list.remove(19); //Removes element at index 19
        System.out.println("Size after removal: " + list.size()); // Output: Size after removal: 10
        System.out.println("Capacity before trimToSize(): " + list.capacity());

        // Trim the ArrayList to its current size
        list.trimToSize();
        System.out.println("Capacity after trimToSize(): " + list.capacity());
    }
}
Size: 20
Capacity: 23  // The actual capacity may vary, but it will be larger than the size.
Size after removal: 10
Capacity before trimToSize(): 23
Capacity after trimToSize(): 10

In this example, we initially created an ArrayList with a capacity of 10. We then added more elements (20) than the initial capacity, which caused the ArrayList to automatically increase its internal array's size. After removing many elements, the capacity was still much larger than the actual number of elements present in the list. Calling `trimToSize()` reduced the capacity to match the current size, saving memory.

Example 2: Trimming an ArrayList with a small initial Capacity

This example demonstrates using trimToSize when the initial capacity is small and it's been expanded considerably

import java.util.ArrayList;

public class TrimToSizeSmallCapacity {
    public static void main(String[] args) {
        // Create an ArrayList with a small initial capacity
        ArrayList<String> names = new ArrayList<>(2);

        // Add elements that exceed the initial capacity
        names.add("Alice");
        names.add("Bob");
        names.add("Charlie");
        names.add("Ram");

        System.out.println("Size: " + names.size());  // Output: Size: 4
        System.out.println("Capacity: " + names.capacity()); // Capacity will be greater than 2 (likely 6 or 8)

        names.trimToSize();
        System.out.println("Capacity after trimToSize(): " + names.capacity());
    }
}
Size: 4
Capacity: 6 // The capacity may vary based on implementation.
Capacity after trimToSize(): 4

Here, we created an ArrayList with an initial capacity of only 2. We then added more than that number of elements. The internal array had to grow beyond the initial size. `trimToSize()` was used to bring the capacity down to match the actual number of elements (4).


Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

You can support this website with a contribution of your choice.

When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M