How to Increase the capacity (size) of ArrayList?
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
import java.util.ArrayList;
public class GFG {
public static void main(String[] arg) throws Exception
{
try {
ArrayList<String> numbers
= new ArrayList<String>( 3 );
numbers.add( "10" );
numbers.add( "20" );
numbers.add( "30" );
System.out.println( "ArrayList: " + numbers);
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
Share your thoughts in the comments
Please Login to comment...