Java ArrayList ensureCapacity(int minCapacity) Method Example

The ensureCapacity(int minCapacity) method of java.util.ArrayList class 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.

Signature

public void ensureCapacity(int minCapacity)

This method 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.

Example

The following example shows the usage of java.util.Arraylist.ensureCapacity(minCapacity) method.

import java.util.ArrayList;

public class EnsureCapacityArrayListExample 
{
    public static void main(String args[]) 
    {
        // Creating an empty array list
        ArrayList al = new ArrayList();
        
        //Adding elements to the arraylist
        al.add("Element1");
        al.add("Element3");
        al.add("Element2");
        al.add("Element4");
        
        // Increase the capacity of the ArrayList to 25 elements
        al.ensureCapacity(25);

        // Print the elements of the arraylist
        System.out.println("**Elements of the ArrayList**");
        for (String val : al) 
        {
            System.out.println(val); 
        }
    }
}

Output

**Elements of the ArrayList**
Element1
Element3
Element2
Element4

Leave a Reply

Your email address will not be published. Required fields are marked *