How to Implement Stack in Java Using Array and Generics?


Java enables the implementation of a stack by utilizing an array and generics. This creates a ve-rsatile and reusable data structure that operates on the principle of Last-In-First-Out (LIFO). In this principle, elements are added and removed from the top. By utilizing an array as its foundation, it ensures efficient memory allocation and access. Additionally, by incorporating generics, the stack becomes capable of accommodating elements of different types, enhancing its versatility.

The implementation involves the definition of a Stack class that incorporates a generic type parameter. It includes essential methods such as push(), pop(), peek(), and isEmpty(). The handling of edge cases, like stack overflow and underflow, is also crucial in ensuring seamless functionality. This implementation empowers developers to create stacks capable of accommodating elements of any type in Java.

Stack in Java

In Java, the stack is a crucial data structure that operates on the principle of Last-In-First-Out (LIFO). It represents a collection of elements where the most recently added element takes precedence in removal. The stack class in Java offers several methods to manipulate elements e-ffectively. For example, the push method allows you to add an element to the top of the stack, while pop removes and returns the topmost element. Additionally, peek enables you to retrieve the top element without removing it, and isEmpty checks if the stack is empty.

import java.util.Stack;

Stack<Type> stack = new Stack<>();
stack.push(element); // Adds 'element' to the top of the stack
Type topElement = stack.pop(); // Removes and returns the top element
Type peekElement = stack.peek(); // Retrieves the top element without removing it
boolean isEmpty = stack.isEmpty(); // Checks if the stack is empty

Approaches

There are different methods to implement stack in Java using Array and Generics and we will look at both the methods in depth:

  • Stack Implementation with Array

  • Stack Implementation with Generics

Stack Implementation with Array

When implementing a stack in Java using an array, one creates a data structure that follows the Last-In-First-Out (LIFO) principle. In this approach, elements are stored within an array, while a top variable is utilized to keep track of the index representing the topmost element in the stack.

The stack class typically incorporates several methods. These include push(), which adds ele-ments to the top of the stack, pop(), used for removing and retrieving the topmost element, pe-ek(), allowing you to view the topmost element without removing it, and isEmpty(), which che-cks if the stack is empty.

Algorithm

  • Create an array to store the elements of the stack.

  • Initialize a variable called "top" to -1, indicating an empty stack.

  • To push an element onto the stack:

  • Check if the stack is full (top == array.length - 1).

  • If the stack is not full, increment the "top" variable by 1 and assign the element to array[top].

  • To pop an element from the stack:

    • Check if the stack is empty (top == -1).

    • If the stack is not empty, retrieve the element from array[top] and decrement the "top" variable by 1.

Example

public class Stack {
   private int[] array;
   private int top;
   
   public Stack(int capacity) {
      array = new int[capacity];
      top = -1;
   }
   
   public void push(int element) {
      if (top == array.length - 1) {
         System.out.println("Stack is full. Cannot push element.");
      } else {
         top++;
         array[top] = element;
         System.out.println("Pushed element: " + element);
      }
   }
   
   public int pop() {
      if (top == -1) {
         System.out.println("Stack is empty. Cannot pop element.");
         return -1;
      } else {
         int poppedElement = array[top];
         top--;
         System.out.println("Popped element: " + poppedElement);
         return poppedElement;
      }
   }
   
   public int peek() {
      if (top == -1) {
         System.out.println("Stack is empty. No element to peek.");
         return -1;
      } else {
         System.out.println("Peeked element: " + array[top]);
         return array[top];
      }
   }
   
   public boolean isEmpty() {
      return (top == -1);
   }
   
   public static void main(String[] args) {
      Stack stack = new Stack(5);
      
      stack.push(10);
      stack.push(20);
      stack.push(30);
      
      stack.pop();
      
      stack.push(40);
      stack.push(50);
      
      stack.pop();
      stack.pop();
      stack.pop();
      stack.pop();
   }
}

Output

Pushed element: 10
Pushed element: 20
Pushed element: 30
Popped element: 30
Pushed element: 40
Pushed element: 50
Popped element: 50
Popped element: 40
Popped element: 20
Popped element: 10

Stack Implementation with Generics

A stack implementation with generics serves as a versatile data structure. It allows for the storage and retrieval of elements in a Last-In-First-Out (LIFO) manner, offering flexibility to handle various data types. By leveraging generics, this adaptable stack becomes an efficient container capable of holding elements of any kind, making it immensely versatile and reusable.

Algorithm

  • A generic class called Stack is created to store elements in a stack.

  • Inside the Stack class, there is a private array or linked list to hold these elements.

  • The stack is initialized with a constructor that allocates the necessary memory.

  • To add an element to the top of the stack, a push(element: T) method is implemented, which increases the stack size and stores the element.

  • Similarly, a pop(): T method is implemented to remove and return the top element from the stack while decreasing its size.

  • The peek(): T method allows retrieving the top element without removing it.

  • Additionally, an isEmpty(): boolean method checks if the stack is empty or not, while size(): number returns how many elements are currently in the stack.

Example

import java.util.ArrayList;
import java.util.EmptyStackException;
import java.util.List;

public class Stack<T> {
   private List<T> stack;

   public Stack() {
      stack = new ArrayList<>();
   }

   public void push(T element) {
      stack.add(element);
   }

   public T pop() {
      if (isEmpty()) {
         throw new EmptyStackException();
      }
      return stack.remove(stack.size() - 1);
   }

   public T peek() {
      if (isEmpty()) {
         throw new EmptyStackException();
      }
      return stack.get(stack.size() - 1);
   }

   public boolean isEmpty() {
      return stack.isEmpty();
   }

   public int size() {
      return stack.size();
   }

   public void clear() {
      stack.clear();
   }

   public static void main(String[] args) {
      Stack<Integer> stack = new Stack<>();

      stack.push(1);
      stack.push(2);
      stack.push(3);

      System.out.println("Stack size: " + stack.size());
      System.out.println("Top element: " + stack.peek());

      while (!stack.isEmpty()) {
         System.out.println("Popped element: " + stack.pop());
      }
   }
}

Output

Stack size: 3
Top element: 3
Popped element: 3
Popped element: 2
Popped element: 1

Conclusion

In conclusion, the utilization of an array and generics in implementing a stack in Java offers the advantages of versatility and type safety. By incorporating generics, developers are able to create a generic class called "Stack" which can accommodate elements of any type, thus enhancing the flexibility of the implementation. This approach ensures that the stack data structure is adaptable to various scenarios while maintaining strict typing constraints.

The stack class uses an array of type T[] to store elements and keeps track of the topmost element using an integer variable called "top". It provides essential methods like push, pop, peek, and isEmpty, ensuring efficient stack operations.

Developers can utilize this implementation to create custom stacks for specific types, all while benefiting from the advantages of type safety. By leveraging arrays and generics, a robust and efficient stack data structure can be achieved in Java.

Updated on: 27-Jul-2023

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements