Open In App

ArrayList ensureCapacity() Method in Java with Examples

Last Updated : 11 Jul, 2025
Comments
Improve
Suggest changes
6 Likes
Like
Report

In Java, the ArrayList.ensureCapacity() method is used to increase the internal capacity of an ArrayList to ensure that it can hold a specified minimum number of elements. It helps to optimize performance by reducing the number of dynamic reallocations when adding a large number of elements.

Example 1: Here, we are using the ensureCapacity() method to preallocate space for an ArrayList of integers before adding elements.

Java
// Java program to demonstrate the use of ensureCapacity()  // method with an ArrayList of Integers import java.util.ArrayList; public class GFG {  public static void main(String[] args) {    // create an ArrayList of Integers  ArrayList<Integer> l = new ArrayList<>();  // preallocate capacity for 5 elements  l.ensureCapacity(5);  // Add elements to the ArrayList  for (int i = 1; i <= 5; i++) {  l.add(i);  }  System.out.println(l);  } } 

Output
[1, 2, 3, 4, 5] 

Explanation: In the above example, we preallocate capacity for an ArrayList of integers before adding 5 elements to optimize memory usage.

Syntax of ensureCapacity() Method

public void ensureCapacity(int minCapacity)

Parameter: minCapacity: The minimum desired capacity for the ArrayList.

Other Examples of Java ArrayList.ensureCapacity()

Example 2: Here, we are using the ensureCapacity() method to preallocate space for a String ArrayList and to add elements.

Java
// Java program to demonstrate the use of ensureCapacity()  // method with an ArrayList of Strings import java.util.ArrayList; public class GFG {  public static void main(String[] args) {    // Create an ArrayList of Strings  ArrayList<String> n = new ArrayList<>();  // Preallocate capacity for 7 elements  n.ensureCapacity(7);  // Add elements to the ArrayList  n.add("Ram");  n.add("Shyam");  n.add("Hari");  System.out.println(n);  } } 

Output
[Ram, Shyam, Hari] 

Explanation: In the above example, we preallocate capacity for an ArrayList of strings and then add a few names to the list.


Example 3: Here, we ensure capacity for an ArrayList when dealing with large data additions.

Java
// Java program to demonstrate the use of ensureCapacity()  // with a large dataset import java.util.ArrayList; public class GFG {  public static void main(String[] args) {    // Create an ArrayList of Integers  ArrayList<Integer> l = new ArrayList<>();  // Preallocate capacity for 200 elements  l.ensureCapacity(200);  // Add 200 elements to the ArrayList  for (int i = 1; i <= 200; i++) {  l.add(i);  }  System.out.println("Size of an ArrayList: " + l.size());  } } 

Output
Size of an ArrayList: 200 

Explanation: In the above example, we preallocate the capacity for an ArrayList to handle a large dataset of 200 elements.


Explore