Java ArrayList ensureCapacity()

The syntax of the ensureCapacity() method is:

arraylist.ensureCapacity(int minCapacity)

Here, arraylist is an object of the ArrayList class.


ensureCapacity() Parameters

The ensureCapacity() takes a single parameter.

  • minCapacity - the specified minimum capacity of the arraylist

ensureCapacity() Return Values

The ensureCapacity() method does not return any value.


Example 1: Java ArrayList ensureCapacity()

import java.util.ArrayList;

class Main {
  public static void main(String[] args) {
    ArrayList<String> languages= new ArrayList<>();

    // set the capacity of the arraylist
    languages.ensureCapacity(3);

    // Add elements in the ArrayList
    languages.add("Java");
    languages.add("Python");
    languages.add("C");
    System.out.println("ArrayList: " + languages);
  }
}

Output

ArrayList: [Java, Python, C]

In the above example, we have created an arraylist named languages. Notice the line,

languages.ensureCapacity(3);

Here, the ensureCapacity() method resized the arraylist to store 3 elements.

However, ArrayList in Java is dynamically resizable. That is, if we add more than 3 elements in the arraylist, it will automatically resize itself. For example,

Example 2: Working of ensureCapacity()

import java.util.ArrayList;

class Main {
  public static void main(String[] args) {
    ArrayList<String> languages= new ArrayList<>();

    // set the capacity of the arraylist
    languages.ensureCapacity(3);

    // Add elements in the ArrayList
    languages.add("Java");
    languages.add("Python");
    languages.add("C");

    // add 4th element
    languages.add("Swift");
    System.out.println("ArrayList: " + languages);
  }
}

Output

ArrayList: [Java, Python, C, Swift]

In the above example, we use the ensureCapacity() method to resize the arraylist to store 3 elements. However, when we add 4th element in the arraylist, the arraylist automatically resizes.

So, why do we need to resize arraylist using the ensureCapacity() method if the arraylist can automatically resize itself?

It is because if we use the ensureCapacity() to resize the arraylist, then the arraylist will be resized at once with the specified capacity. Otherwise, the arraylist will be resized every time when an element is added.

Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges