Coders Packet

Generic Stack implementation using Generic class in Java

By Gurleen Kaur

A generic stack accepts any data type the user wants his/her input to be in. It helps the user use a single stack class to create multiple stacks with varying input datatypes.

This project has the basic push, pop, and view options. The users first need to select the data type they require. 

A generic class named PushPop is created in which a generic object, 'a', is declared. The variable 'top' is used as a pointer for the stack. 

Generic class declaration: 

class PushPop {
static final int MAX = 20;
int top;
int i=0;
X[] a = (X[])new Object[MAX];
PushPop(){
top = -1;
}

If top=-1, the stack is empty.

In the main class, the user choices for the data type, the number of inputs, and operations are taken. 

If the user chooses to pop, the value of 'top' is checked. If 'top' is less than zero, the stack is empty and a stack underflow condition takes place. If 'top' is greater than or equal to zero, the topmost element is popped out (removed from the stack). 

 If the user chooses to push inputs, the value of 'top' is checked. If 'top' is greater than the maximum value (array size 'MAX'), a stack overflow condition is reached. If 'top' is less than the maximum value, the user input is pushed into the stack (added to the stack).

Output

 

Download Complete Code

Comments

No comments yet

Download Packet

Reviews Report

Submitted by Gurleen Kaur (gurleen7291)

Download packets of source code on Coders Packet