The
Stack
class is astack of objects. Last-In-First-Out (LIFO) The element inserted first is processed last and the element inserted last is processed first.
The setSize
method changes the size of the Stack
object.
public void setSize(int newSize)
This method takes the new size of the Stack
object as an argument.
size
is greater than the current stack
size, then null elements are added in the new places.size
is lesser than the current stack
size, then all the elements at the index size and above are removed from the stack
.This method doesn’t return any value.
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.