What is the Stack.setSize method in Java?

The Stack class is a Last-In-First-Out (LIFO)The element inserted first is processed last and the element inserted last is processed first. stack of objects.

The setSize method changes the size of the Stack object.

Syntax

public void setSize(int newSize)

Parameters

This method takes the new size of the Stack object as an argument.

  • If the size is greater than the current stack size, then null elements are added in the new places.
  • If the size is lesser than the current stack size, then all the elements at the index size and above are removed from the stack.

Return value

This method doesn’t return any value.

Code

import java.util.Stack;
import java.util.ArrayList;
class SetSize {
public static void main( String args[] ) {
Stack<Integer> stack = new Stack<>();
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
System.out.println("The stack is "+ stack);
System.out.println("The size is "+ stack.size());
stack.setSize(2);
System.out.println("\nThe stack is "+ stack);
System.out.println("The size is "+ stack.size());
stack.setSize(4);
System.out.println("\nThe stack is "+ stack);
System.out.println("The size is "+ stack.size());
}
}

In the code above,

  • In line number 1 : We import the Stack class.

  • From line number 5 to 9: We create a new Stack object with the name stack and add four elements (1,2,3,4) to the stack object using the push method. Now the size of the stack is 4.

  • In line number 14: We use the setSize method to change the size of the stack object from 4 to 2. The elements present in index 2 and after will be removed from the stack and the size becomes 2.

  • In line number 19: We use the setSize method to change the size of the stack object from 2 to 4. There are already 2 elements present in the stack. For the new 2 positions, the null is inserted.

Free Resources