ArrayList ensureCapacity() Method in Java

Published by user on

ArrayList ensureCapacity() is used to increase the capacity of the list. A call to this method makes sure that ArrayList can hold at least the number of elements specified by the minimum capacity argument. Before adding a large number of elements to List you can call this method to avoid incremental allocation.

The default capacity of an ArrayList is 10. Whenever the size of ArrayList reaches capacity * load factor, the list doubles its capacity. You can make use of ensureCapacity if you don’t want to double the space every time. If used correctly it increases the performance of the application.

Syntax:

public void ensureCapacity(int minCapacity)

parameter – minCapacity is the capacity you want.

ArrayList ensureCapacity() Example

The below program makes sure that the list can hold at least 15 elements. Don’t pass a very large number to this method otherwise, you will get Exception in thread “main” java.lang.OutOfMemoryError: Java heap space.

import java.util.ArrayList;

public class ArrayListStringDemo {

	public static void main(String[] args) {
		ArrayList<String> employees = new ArrayList<>();
		employees.add("Richard");
		employees.add("Stevan");
		employees.add("Joseph");
		// ensures that this arraylist can hold at
		// least 12 elements
		employees.ensureCapacity(12);
		employees.add("Charles");
		System.out.println("ArrayList elements: " + employees);
	}
}

Output:

ArrayList elements: [Richard, Stevan, Joseph, Charles]

ArrayList ensurecapacity

Before calling addAll() you can call ensureCapacity() method to make sure enough capacity is available, the size of ArrayList still remains the same.

Further Reading:

ArrayList Documentation

Categories: Java