The ensureCapacity() method of java.util.ArrayList class increases the capacity of this 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.
Below are the examples to illustrate the ensureCapacity() method.
Example 1:
import java.util.*;
public class GFG1 {
public static void main(String[] argv)
throws Exception
{
try {
ArrayList<Integer>
arrlist = new ArrayList<Integer>();
arrlist.add( 10 );
arrlist.add( 20 );
arrlist.add( 30 );
arrlist.add( 40 );
System.out.println( "ArrayList: "
+ arrlist);
arrlist.ensureCapacity( 5000 );
System.out.println( "ArrayList can now"
+ " surely store upto"
+ " 5000 elements." );
}
catch (NullPointerException e) {
System.out.println( "Exception thrown : " + e);
}
}
}
|
Output:
ArrayList: [10, 20, 30, 40]
ArrayList can now surely store upto 5000 elements.
Example 2:
import java.util.*;
public class GFG1 {
public static void main(String[] argv)
throws Exception
{
try {
ArrayList<String>
arrlist = new ArrayList<String>();
arrlist.add( "A" );
arrlist.add( "B" );
arrlist.add( "C" );
arrlist.add( "D" );
System.out.println( "ArrayList: "
+ arrlist);
arrlist.ensureCapacity( 400 );
System.out.println( "ArrayList can now"
+ " surely store upto"
+ " 400 elements." );
}
catch (NullPointerException e) {
System.out.println( "Exception thrown : " + e);
}
}
}
|
Output:
ArrayList: [A, B, C, D]
ArrayList can now surely store upto 400 elements.