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.

Syntax

The syntax of ensureCapacity() method is

ArrayList.ensureCapacity(int minCapacity)

where

ParameterDescription
minCapacityThe desired minimum capacity for this ArrayList.

Returns

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"));
		arrayList.ensureCapacity(500);
		System.out.println("It is ensured that arrayList can hold a minimum capcity of 500.");
    }  
}

Output

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

Conclusion

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.