Skip to content
Related Articles

Related Articles

Improve Article

How to Increase the capacity (size) of ArrayList?

  • Last Updated : 02 Dec, 2020

ArrayList class is a resizable array, present in java.util package. The difference between an array and an ArrayList in Java, is that the size of an array cannot be modified (i.e. if you want to append/add or remove element(s) to/from an array, you have to create a new array. However, elements can be added/appended or removed from an ArrayList without the need to create a new array.

Whenever an instance of ArrayList in Java is created then by default the capacity of Arraylist is 10. Since ArrayList is a growable array, it automatically resizes itself whenever a number of elements in ArrayList grow beyond a threshold. However, ensureCapacity() method of java.util.ArrayList class can be used to increase the capacity of an ArrayList instance, if necessary, to ensure that it can hold at least the number of elements specified by the minimum capacity argument.


public void ensureCapacity(int minCapacity)

Parameters: This method takes the desired minimum capacity as a parameter.

Return Type: This method does not return any value.



// Java program to demonstrate
// ensureCapacity() method for String values
import java.util.ArrayList;
public class GFG {
    public static void main(String[] arg) throws Exception
        try {
            // Creating object of ArrayList of String of
            // size = 3
            ArrayList<String> numbers
                = new ArrayList<String>(3);
            // adding element to Arrlist numbers
            // Print the ArrayList
            System.out.println("ArrayList: " + numbers);
            // using ensureCapacity() method to
            // increase the capacity of ArrayList
            // numbersto hold 500 elements.
                "Increasing the capacity of ArrayList numbers to store upto 500 elements.");
                "ArrayList numbers can now store upto 500 elements.");
        catch (NullPointerException e) {
            System.out.println("Exception thrown : " + e);
ArrayList: [10, 20, 30]
Increasing the capacity of ArrayList numbers to store upto 500 elements.
ArrayList numbers can now store upto 500 elements.

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :