Stack
- It is the child class of Vector.
- Whenever last in first out(LIFO) order required then we should go for Stack.
Constructors
Stack class contains one and only one constructor.
Stack s= new Stack();
Methods in Stack
1. Object push(Object o);
To insert an object into the stack.
2. Object pop();
To remove and return top of the stack.
3. Object peek();
To return top of the stack without removal.
4. boolean empty();
Returns true if Stack is empty.
5. int search(Object o);
Returns offset if the element is available otherwise returns “-1”
package com.ashok.collections; import java.util.Stack; /** * * @author ashok.mariyala * */ public class MyStack { public static void main(String[] args) { Stack stack = new Stack(); stack.push("Ashok"); stack.push("Vinod"); stack.push("Naresh"); System.out.println(stack);// [Ashok, Vinod, Naresh] System.out.println(stack.pop());// Naresh System.out.println(stack);// [Ashok, Vinod] System.out.println(stack.peek());// Vinod System.out.println(stack.search("Ashok"));// 2 System.out.println(stack.search("Dillesh"));// -1 System.out.println(stack.empty());// false } }
Stack Class