Program
import java.util.Stack; public class StackExamples { public static void main(String[] args) { Stack<String> stk = new Stack<>(); stk.push("Daisy"); stk.push("Ruth"); stk.push("Major"); stk.push("Joe"); System.out.println("Stack: " + stk); //push() stk.push("Bob"); stk.push("Minni"); System.out.println("\nPush Stack:"+stk); //pop() System.out.println("\nElement popped: " + stk.pop()); System.out.println("\nPop Stack: " + stk); //search() int location = stk.search("Ruth"); System.out.println("\nLocation of Ruth:" + location); //size() int x = stk.size(); System.out.println("\nThe size is:" + x); //empty() boolean result = stk.empty(); result = stk.empty(); System.out.println("\nThe empty set is:" + result); } }
Output
Stack: [Daisy, Ruth, Major, Joe] Push Stack:[Daisy, Ruth, Major, Joe, Bob, Minni] Element popped: Minni Pop Stack: [Daisy, Ruth, Major, Joe, Bob] Location of Ruth:4 The size is:5 The empty set is:false
Description
public E push‹(E item)
Pushes an item onto the top of this stack. This has exactly the same effect as:
addElement(item)
Parameters:
item – the item to be pushed onto this stack.
Returns:
the item argument.
public E pop()
Removes the object at the top of this stack and returns that object as the value of this function.
Returns:
The object at the top of this stack (the last item of the Vector object).
Throws:
EmptyStackException – if this stack is empty.
public int search‹(Object o)
Returns the 1-based position where an object is on this stack. If the object o occurs as an item in this stack, this method returns the distance from the top of the stack of the occurrence nearest the top of the stack; the topmost item on the stack is considered to be at distance 1. The equals method is used to compare o to the items in this stack.
Parameters:
o – the desired object.
Returns:
the 1-based position from the top of the stack where the object is located; the return value -1 indicates that the object is not on the stack.
public int size()
Returns the number of components in this vector.
Specified by:
size in interface Collection<E>
Specified by:
size in interface List<E>
Parameters:
value – value whose presence in this map is to be tested
public boolean empty()
Tests if this stack is empty.
Returns:
true if and only if this stack contains no items; false otherwise.