Java ArrayList ensureCapacity() Method

Java ArrayList Java ArrayList

The ensureCapacity() method is used to set the dynamic array to have a specified capacity size.

The syntax of the ensureCapacity() method is:

arraylist.ensureCapacity(int minCapacity)

Note:arraylist is an object of the ArrayList class.

Parameter Description:

  • minCapacity - the capacity of the dynamic array

Return Value

No return value.

Example

ArrayList sureCapacity() usage example:

Example

import java.util.ArrayList;
class Main {
    public static void main(String[] args){

        // Create a dynamic array
        ArrayList<String> sites = new ArrayList<>();
       
        // Set the capacity size of the arraylist
        sites.ensureCapacity(3);
       
        sites.add("Google");
        sites.add("Example");
        sites.add("Taobao");
        System.out.println("Website list: " + sites);
    }
}

Executing the above program produces the following output:

网站列表: [Google, Example, Taobao]

In the above example, we created an array named sites.

Note this line:

sites.ensureCapacity(3);

We use the ensureCapacity() method to adjust the size of the dynamic array to be able to store 3 elements.

An ArrayList in Java can dynamically adjust its size. That is, if we add more than 3 elements to the arraylist, it will automatically adjust its size, for example:

Example

import java.util.ArrayList;
class Main {
    public static void main(String[] args){

        // Create a dynamic array
        ArrayList<String> sites = new ArrayList<>();
       
        // Set the capacity size of the arraylist
        sites.ensureCapacity(3);
       
        sites.add("Google");
        sites.add("Example");
        sites.add("Taobao");
       
        // Add the fourth element
        sites.add("Wiki");

        System.out.println("Website list: " + sites);
    }
}

Executing the above program produces the following output:

网站列表: [Google, Example, Taobao, Wiki]

In the above example, we use the ensureCapacity() method to adjust the size of the dynamic array to store 3 elements. However, when we add a 4th element to the arraylist, the arraylist adjusts its size automatically.

Then, if the arraylist can automatically adjust its size, why do we still need to use the ensureCapacity() method to adjust the size of the arraylist?

This is because if we use the ensureCapacity() method to adjust the size of the arraylist, the arraylist will immediately adjust to the specified capacity. Otherwise, the size of the arraylist will be adjusted every time an element is added.

Java ArrayList Java ArrayList

Other Extensions