Home > Java > javaTutorial > body text

How to implement stack in Java using arrays and generics?

WBOY
Release: 2023-09-05 21:25:06
forward
1078 people have browsed it

How to implement stack in Java using arrays and generics?

Java implements the stack by leveraging arrays and generics. This creates a versatile and reusable data structure that operates on the last-in-first-out (LIFO) principle. Following this principle, elements are added and removed from the top. By utilizing arrays as the basis, it ensures efficient memory allocation and access. Additionally, by incorporating generics, the stack is able to accommodate elements of different types, thereby enhancing its versatility.

The implementation involves the definition of the Stack class containing generic type parameters. It includes basic methods such as push(), pop(), peek() and isEmpty(). Handling of edge cases, such as stack overflows and underflows, is also critical to ensure seamless functionality. This implementation enables developers to create stacks that can accommodate any type of element in Java.

Stack in Java

In Java, the stack is an important data structure that operates on the last-in-first-out (LIFO) principle. It represents a collection of elements where the most recently added elements are removed first. The stack class in Java provides a variety of methods for efficiently manipulating elements. 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
Copy after login

method

There are different ways to implement a stack in Java using arrays and generics, we will delve into both of them:

  • Use array to implement stack

  • Use generics for stack implementation

Use array to implement stack

When implementing a stack in Java using an array, a data structure is created that follows the last-in-first-out (LIFO) principle. In this approach, elements are stored in an array, and the top variable is used to keep track of the index that represents the topmost element in the stack.

Stack classes usually contain multiple methods. These include push(), which adds an element to the top of the stack, pop(), which removes and retrieves the top element, pe-ek(), which allows you to view the top element without removing it, and isEmpty ( ), which checks whether the stack is empty.

algorithm

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

  • Initialize the variable named "top" to -1, indicating that the stack is empty.

  • Push elements 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].

  • 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();
   }
}
Copy after login

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
Copy after login

Use generics for stack implementation

A stack implementation with generics can be used as a general purpose data structure. It allows elements to be stored and retrieved in a last-in-first-out (LIFO) manner, providing flexibility in handling a variety of data types. By leveraging generics, this adaptable stack becomes an efficient container capable of holding elements of any type, making it extremely versatile and reusable.

algorithm

  • Create a generic class named Stack to store elements on the stack.

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

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

  • To add an element to the top of the stack, you need to implement the push(element: T) method, which increases the stack size and stores the element.

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

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

  • In addition, the isEmpty(): boolean method checks whether the stack is empty, 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());
      }
   }
}
Copy after login

Output

Stack size: 3
Top element: 3
Popped element: 3
Popped element: 2
Popped element: 1
Copy after login

in conclusion

In short, using arrays and generics to implement stacks in Java has the advantages of versatility and type safety. By incorporating generics, developers can create a generic class called "Stack" that can hold elements of any type, thereby increasing implementation flexibility. This approach ensures that the stack data structure can adapt to various scenarios while maintaining strict type constraints.

The stack class uses an array of type T[] to store elements and an integer variable called "top" to keep track of the topmost element. It provides basic methods such as push, pop, peek, isEmpty, etc. to ensure efficient stack operations.

Developers can leverage this implementation to create custom stacks for specific types while benefiting from the advantages of type safety. Robust and efficient stack data structures can be implemented in Java by leveraging arrays and generics.

The above is the detailed content of How to implement stack in Java using arrays and generics?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template