VOOZH about

URL: https://www.geeksforgeeks.org/java/arraylist-ensurecapacity-method-in-java-with-examples/

⇱ ArrayList ensureCapacity() Method in Java with Examples - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

ArrayList ensureCapacity() Method in Java with Examples

Last Updated : 11 Jul, 2025

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.


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.


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.


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.

Comment