Java Utility Library

Java Stack - setSize() Method



The java.util.Stack.setSize() method is used to set the size of the stack. If the new size is greater than the current size, new null items are added to the top of the stack. If the new size is less than the current size, all components at index newSize and greater are discarded.

Syntax

public void setSize(int newSize)

Parameters

newSize Specify new size of the stack.

Return Value

void type.

Exception

Throws ArrayIndexOutOfBoundsException, if the new size is negative.

Example:

In the example below, the java.util.Stack.setSize() method is used to set the size of the stack called MyStack.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating a stack
    Stack<Integer> MyStack = new Stack<Integer>();

    //populating stack
    MyStack.push(10);
    MyStack.push(20);
    MyStack.push(30);
    MyStack.push(40);
    MyStack.push(50);

    System.out.println("MyStack contains: " + MyStack);
    MyStack.setSize(3);
    System.out.println("MyStack contains: " + MyStack);    
    MyStack.setSize(5);
    System.out.println("MyStack contains: " + MyStack);  
  }
}

The output of the above code will be:

MyStack contains: [10, 20, 30, 40, 50]
MyStack contains: [10, 20, 30]
MyStack contains: [10, 20, 30, null, null]

❮ Java.util - Stack