What is the Stack.setSize method in Java?
The
Stackclass 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.
Syntax
public void setSize(int newSize)
Parameters
This method takes the new size of the Stack object as an argument.
- If the
sizeis greater than the currentstacksize, then null elements are added in the new places. - If the
sizeis lesser than the currentstacksize, then all the elements at the index size and above are removed from thestack.
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
Stackclass. -
From line number 5 to 9: We create a new
Stackobject with the namestackand add four elements (1,2,3,4) to thestackobject using thepushmethod. Now the size of thestackis4. -
In line number 14: We use the
setSizemethod to change the size of thestackobject from 4 to2. The elements present in index2and after will be removed from the stack and thesizebecomes2. -
In line number 19: We use the
setSizemethod to change the size of thestackobject from2to4. There are already 2 elements present in thestack. For the new 2 positions, thenullis inserted.