100% Placement assistance on AUTOMATION TESTING WITH JAVA+selenium

Abstract Data Types Program in Java – Brief Guide

Abstract Data Types Programs in Java

Sure! Here’s an example of implementing an abstract data type, specifically a stack, in Java:

public class Stack<T> {
    private int top;
    private int maxSize;
    private T[] stackArray;
    public Stack(int maxSize) {
        this.top = -1;
        this.maxSize = maxSize;
this.stackArray = (T[]) new Object[maxSize];
    }
    public void push(T item) {
        if (top == maxSize - 1) {      
System.out.println("Abstract Data Types
  • Stack is full. Cannot push element: " + item); return; } stackArray[++top] = item; System.out.println("Pushed element: " + item); } public T pop() { if (top == -1) { System.out.println("Stack is empty. Cannot pop element."); return null; } T item = stackArray[top--]; System.out.println("Popped element: " + item); return item; } public T peek() { if (top == -1) { System.out.println("Stack is empty."); return null; } return stackArray[top]; } public boolean isEmpty() { return (top == -1); } public boolean isFull() { return (top == maxSize - 1); } public int size() { return top + 1; } public static void main(String[] args) { Stack<Integer> stack = new Stack<>(5); stack.push(1); stack.push(2); stack.push(3); System.out.println("Stack size: " + stack.size()); System.out.println("Top element: " + stack.peek()); stack.pop(); stack.pop(); stack.pop(); stack.pop(); System.out.println("Is stack empty? " + stack.isEmpty()); } }
  • Abstract Data Types Program in Java Explanation:

    In this example, we create a generic Stack class that can work with elements of any type T. The class contains push, pop, peek, isEmpty, isFull, and size methods. The stack is implemented using an array, and the maximum size of the stack is specified during initialization.

    In the primary method, we create an instance of the Stack class and perform stack operations like pushing elements, popping elements, peeking at the top element, checking if the stack is empty, etc.

    Note: When creating a generic array, like T[] stackArray, we need to use type casting (T[]) new Object[maxSize] due to type erasure in Java. This can lead to a compiler warning, but it’s safe to ignore it.

    Feel free to modify and expand upon this example to suit your needs or implement other abstract data types.

    100% Placement assistance on AUTOMATION TESTING WITH JAVA+selenium

    Click Here to Leave a Comment Below 0 comments

    Leave a Reply: