Yandex

Java Advanced ConceptsJava Advanced Concepts3

Java ArrayList ensureCapacity() method
Syntax and Examples


Introduction

The `ensureCapacity()` method in Java's ArrayList is a handy way to proactively manage memory. Think of an ArrayList like a dynamically growing container for objects. When you add more elements than it currently has space for, the ArrayList needs to create a larger underlying array and copy everything over. This can be inefficient if you know roughly how many elements you'll be adding later.

The `ensureCapacity()` method lets you reserve space in advance, potentially avoiding those costly resizing operations. It doesn't add any elements – it just makes sure that the ArrayList has enough capacity to hold at least the specified number of elements without needing to reallocate immediately.

Syntax

    
public void ensureCapacity(int minCapacity)
    
  

Parameters

Parameter Description
minCapacity The minimum capacity that the ArrayList should have. This value must be non-negative. If it's larger than the current capacity, the internal array is resized to accommodate it.

Return Value

The ensureCapacity() method returns void (nothing). It modifies the ArrayList's internal capacity directly.

Examples

Example 1: Pre-reserving Capacity

This example demonstrates how to use `ensureCapacity()` before adding a large number of elements. We want to add 1000 elements, so we reserve space for them beforehand.


ArrayList<String> myList = new ArrayList<>();
myList.ensureCapacity(1000); // Reserve space for 1000 elements

for (int i = 0; i < 1000; i++) {
    myList.add("Element " + i);
}

  
No output is printed to console.

Explanation: We create an ArrayList and immediately call ensureCapacity(1000). This tells the ArrayList that we anticipate needing space for at least 1000 elements. Then, we add 1000 strings to the list. Because we reserved capacity beforehand, adding these elements is likely faster than if we had let the ArrayList resize itself repeatedly during the addition process.

Example 2: Ensuring Capacity Beyond Current Size

This example shows what happens when you call `ensureCapacity()` with a value larger than the current size of the list.


ArrayList<Integer> numbers = new ArrayList<>(5); // Initial capacity of 5
numbers.add(1);
numbers.add(2);
numbers.add(3);
System.out.println("Current size: " + numbers.size());
System.out.println("Current capacity: " + numbers.size());
numbers.ensureCapacity(10); // Increase capacity to 10
System.out.println("New capacity: " + numbers.size());

  
Current size: 3
Current capacity: 3
New capacity: 10

Explanation: We initialized an ArrayList with a starting capacity of 5. Then we added 3 elements, so the current size is 3 and the current capacity is also 3. Calling ensureCapacity(10) increases the underlying array's capacity to 10. Note that the `size()` method returns the number of elements currently in the list (which remains 3), while `ensureCapacity()` affects only the allocated memory.

Example 3: Using with Known Data Size

This example shows how to use ensure capacity if you are reading data from a file or database and know approximately how many elements will be added.


int expectedDataSize = 500;
ArrayList<Double> data = new ArrayList<>();

data.ensureCapacity(expectedDataSize);

// Simulate reading data from a file or database
for (int i = 0; i < expectedDataSize; i++) {
    data.add(Math.random() * 100); // Add some random double values
}

  
No output is printed to console.

Explanation: Imagine you're reading a file and know it contains approximately 500 data points. Calling ensureCapacity(expectedDataSize) allows the ArrayList to preallocate enough space, avoiding potential resizing overhead during the read process.


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