Stack Class in Java with Program Example

Stack extends Vector class that implements Last in first out (LIFO) data structure, introduced in JDK 1.0. The data structure specifies the last element to be added to the stack, is the first one to be removed. It is a subclass of the Vector class that enables it to inherit all the attributes and methods of its parent class. It is considered as a legacy class as it exist even before the collection framework and it is re-engineered to support the collection.

Screenshot from 2023 07 04 19 23 17

Further, it provides only a default constructor to create an empty stack object.

One of the main use case of the Stack class is to reverse a sequence of elements. This can be done by pushing elements onto the stack and then popping them off one by one from the top.

The collection class provides various methods for manipulating elements present in the stack, such as push(), pop(), peek(), and empty().

Methods Of Stack Class

push(): The push method is used to add an element to the top of the stack

pop(): The pop method is used to remove and return the element at the top.

peek(): The peek method returns the element at the top without removing it.

empty(): It returns true if the stack is empty, otherwise, false.

search(): It searches an element, and returns offset, otherwise, -1 to signify not found.

Other Inherited Methods

MethodsExplanation
addElement(T obj)Inserts an element to the end of the list.
removeElement( T obj)Removes the very first occurrence of the given element
trimToSize()Reduces the capacity of the given vector to the current size
ensureCapacity(int minCapacity)Increases the capacity to ensure that the list can hold at least the specified number of elements
setSize()Set the size of the given vector, storing null values to new empty spaces
capacity()Returns the current capacity of the vector
insertElementAt(T obj, int indx)Inserts the given element at the specified position, moving elements greater than that index by 1
removeElementAt(int indx)Deletes the element at the specified index
setElementAt(T obj, int indx)Replaces the element at the specified position with the specified element
elementAt(int indx)Returns the element at the given position
firstElement()Returns the first element in the list
lastElement()Returns the last element in the list
copyInto(Object[] o)Copies elements to the given arrays passed as parameter
indexOf(T o)Returns the index of the first occurrence of the specified element
add(T obj)It inserts an element to the end and returns true if it's added successfully
add(int indx, T obj)It inserts the given element at the specified index of the list
addAll(Collection c)It adds entire compatible collection objects to the end of the list
addAll(int indx, Collection c)It inserts all the compatiable collection objects at the given index in the list
clear()It removes or truncates all the elements from the given list
contains(Object obj)It returns true if the given object is present within the list
containsAll(Collection obj)It returns true if all the elements in the given collection are present in the list
equals(Object obj)It returns true if the given object is equivalent to the list
hashCode()It returns hashcode of a list
indexOf(Object c)It returns the index of the given object which matches first, oterwise -1 is returned
isEmpty()It checks whether a list contains any element or not.
iterator()It returns iterator object for a list
lastIndexOf(Object obj)It returns index of the given object which match first from the last, otherwise, -1 is returned
listIterator()It returns object of ListIterator
listIterator(int indx)It returns listIterator object with the starting point specified with indx.
remove(int index)It removes an element from the specified position and returns the removed object from the list
remove(Object obj)It removes very first occurrence of the given object from the list.
removeAll(Collection obj)It removes all the elements that are present in the given collection from the list
replaceAll(UnaryOperator operator)It replaces all the elements by performing the given operator to them in the list
retainAll(Collection c)It retains all the elements that matches in the given list and removes all others from the list
set(int indx, T obj)It replaces the given object at specified position and returns the replaced object.
size()It returns number of elements present in the list
sort(Comparator c)It sorts the list based on given order specified in the comparator.
spliIterator()It returns SplitIterator object
subList(int from, int to)It returns sublist that falls between fromIndx and toIndex
toArray()t converts and returns an array corresponding to the given list

Here’s a program example to reverse a sequence of integers using Stack:

Program: 

import java.util.Stack;

public class Main
{
  public static void main (String[]args)
  {
    Stack < Integer > stack = new Stack <> ();
    stack.push (1);
    stack.push (2);
    stack.push (3);
    stack.push (4);
    while (!stack.empty ())
      {
  System.out.println ("Element :: "+ stack.pop ());
      }
  }
}

Output:

Element :: 4
Element :: 3
Element :: 2
Element :: 1

Over Stack class, the Deque interface should be used as it provides a more complete and flexible API. The Deque interface extends the Queue interface and supports both LIFO and First-In-First-Out (FIFO) operations. The ArrayDeque class implements the Deque interface which is a resizable array and is a good choice for most use cases.

Here’s a program code to reverse a sequence of integers  using the ArrayDeque class:
Program:
import java.util.ArrayDeque;
public class Main
{
  public static void main (String[]args)
  {
    ArrayDeque < Integer > deque = new ArrayDeque <> ();
    deque.push (1);
    deque.push (2);
    deque.push (3);
    deque.push (4);
    while (!deque.isEmpty ())
      {
  System.out.println ("Element :: "+deque.pop ());
      }
  }
}
Output:
Element :: 4
Element :: 3
Element :: 2
Element :: 1

 

Leave a Reply