Stack ensureCapacity() method in Java with Example
Last Updated :
24 Dec, 2018
The ensureCapacity() method of Java.util.Stack class increases the capacity of this Stack 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 {
Stack<Integer>
stack = new Stack<Integer>();
stack.add( 10 );
stack.add( 20 );
stack.add( 30 );
stack.add( 40 );
System.out.println( "Stack: "
+ stack);
stack.ensureCapacity( 5000 );
System.out.println( "Stack can now"
+ " surely store upto"
+ " 5000 elements." );
}
catch (NullPointerException e) {
System.out.println( "Exception thrown : " + e);
}
}
}
|
Output:
Stack: [10, 20, 30, 40]
Stack can now surely store upto 5000 elements.
Example 2:
import java.util.*;
public class GFG1 {
public static void main(String[] argv)
throws Exception
{
try {
Stack<String>
stack = new Stack<String>();
stack.add( "A" );
stack.add( "B" );
stack.add( "C" );
stack.add( "D" );
System.out.println( "Stack: "
+ stack);
stack.ensureCapacity( 400 );
System.out.println( "Stack can now"
+ " surely store upto"
+ " 400 elements." );
}
catch (NullPointerException e) {
System.out.println( "Exception thrown : " + e);
}
}
}
|
Output:
Stack: [A, B, C, D]
Stack can now surely store upto 400 elements.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...