Call: +91-9992448483| Email: admin@pyarb.com

Stack in Java collection


Stack is most popular data structure in computer. Stack in Java collection framework is a class that extends Vector class. Stack is a class implements Serializable, Clonneable,Iterable<>, Collection<>, RAndomAccess and List<> intefaces.

Stack in Java collection
Stack in Java collection

Constructor

Stack has only one constructor.

Stack(); This creates an empty stack.

Methods In Stack class

There are only five methods in Stack class. These are

  1. push(): This method takes an object as argument which is inserted in stack at top location. This method returns the same object in the argument.
  2. pop(); This method deletes and returns object at the top position in stack. When we try to call pop method in empty stack, jvm throws EmptyStackException.
  3. peek(); this method take no argument and return the object at the top position without deleting it. Jvm throws EmptyStackException exception if we try to call peek method in an empty stack.
  4. empty(); This method checks whether the stack is empty or not and return true if stack is empty. Otherwise it will return false.
  5. search(); We have to pass object to be searched as argument and then this method search stack for that object. If object is found it returns the position of that object as an positive integer. If it do not find desired object it will return -1.

Lets look at following demo example to get clear idea about methods of Stack in Java collection.

Output of this program will be like this.

I hope every thing is clear in this example where a stack s is created and two string objects are pushed and poped. The only thing that we have to understand is bit about search method.

Search method counts downward from the top of stack start from 1. So when searching object “Log” in above example we get output 2.

Comment down below if you have any query.

Have any Question or Comment?

Leave a Reply

Your email address will not be published. Required fields are marked *