Java ArrayList.ensureCapacity() – Examples

In this tutorial, we will learn about the Java ArrayList.ensureCapacity() method, and learn how to use this method to ensure the capacity of this ArrayList, with the help of examples.

ensureCapacity(int minCapacity)

ArrayList.ensureCapacity() increases the capacity of this ArrayList instance, if necessary, to ensure that it can hold at least the number of elements specified by the minimum capacity argument.

ArrayList by default is dynamic and store any number of elements in it. ensureCapacity() guarantees that this ArrayList can hold specified number of elements.


The syntax of ensureCapacity() method is

ArrayList.ensureCapacity(int minCapacity)


minCapacityThe desired minimum capacity for this ArrayList.


The method returns void.

Example 1 – ensureCapacity(int minCapacity)

In this example, we will define a ArrayList of Strings and initialize it with some elements in it. The we shall check if element "c" is present in this ArrayList using contains() method. Since, the element is present in the HashSet, contains() method should return true.

Java Program

import java.util.ArrayList;
import java.util.Arrays;

public class Example {  
	public static void main(String[] args) {
		ArrayList<String> arrayList = new ArrayList<String>(Arrays.asList("a", "b", "c"));
		System.out.println("It is ensured that arrayList can hold a minimum capcity of 500.");


It is ensured that arrayList can hold a minimum capcity of 500.


In this Java Tutorial, we have learnt the syntax of Java ArrayList.ensureCapacity() method, and also learnt how to use this method with the help of examples.