Open In App

How to Increase the capacity (size) of ArrayList?

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

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.

Syntax:

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.

Example:

Java




// 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
            numbers.add("10");
            numbers.add("20");
            numbers.add("30");
  
            // Print the ArrayList
            System.out.println("ArrayList: " + numbers);
  
            // using ensureCapacity() method to
            // increase the capacity of ArrayList
            // numbersto hold 500 elements.
            System.out.println(
                "Increasing the capacity of ArrayList numbers to store upto 500 elements.");
  
            numbers.ensureCapacity(500);
  
            System.out.println(
                "ArrayList numbers can now store upto 500 elements.");
        }
  
        catch (NullPointerException e) {
            System.out.println("Exception thrown : " + e);
        }
    }
}


Output

ArrayList: [10, 20, 30]
Increasing the capacity of ArrayList numbers to store upto 500 elements.
ArrayList numbers can now store upto 500 elements.


Last Updated : 02 Dec, 2020
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads