The setSize() method of Java.util.Stack class changes the size of this Stack instance to the size passed as the parameter.
Syntax:
public void setSize(int size)
Parameters: This method takes the new size as a parameter.
Exception: This method throws ArrayIndexOutOfBoundsException if the new size is negative.
Below are the examples to illustrate the setSize() method.
Example 1:
import java.util.*;
public class GFG1 {
public static void main(String[] argv)
{
try {
Stack<Integer>
stack = new Stack<Integer>();
stack.add( 10 );
stack.add( 20 );
stack.add( 30 );
stack.add( 40 );
System.out.println( "Stack: " + stack);
System.out.println( "Current size of Stack: "
+ stack.size());
stack.setSize( 10 );
System.out.println( "New size of Stack: "
+ stack.size());
}
catch (Exception e) {
System.out.println( "Exception thrown : " + e);
}
}
}
|
Output:
Stack: [10, 20, 30, 40]
Current size of Stack: 4
New size of Stack: 10
Example 2:
import java.util.*;
public class GFG1 {
public static void main(String[] argv)
{
try {
Stack<String>
stack = new Stack<String>();
stack.add( "A" );
stack.add( "B" );
stack.add( "C" );
stack.add( "D" );
System.out.println( "Stack: "
+ stack);
System.out.println( "Current size of Stack: "
+ stack.size());
stack.setSize(- 1 );
System.out.println( "New size of Stack: "
+ stack.size());
}
catch (Exception e) {
System.out.println( "Exception thrown : " + e);
}
}
}
|
Output:
Stack: [A, B, C, D]
Current size of Stack: 4
Exception thrown : java.lang.ArrayIndexOutOfBoundsException: -1