/* ************************************************************** How to implement a GENERIC stack with arrays ************************************************************** */ public class ArrayStack implements MyStackInterface { private T[] item; private int stackTop; public ArrayStack(int N) { // ************************************************ // Should be: item = new T[N]; // But this is illegal due to "type erasure" // This is a hack to make it work with a warning // ************************************************ item = (T[]) new Object[N]; // Create an array of Object and cast stackTop = 0; } public boolean isEmpty() // returns true is stack is empty { return stackTop == 0; } public boolean isFull() // returns true is stack is full { return stackTop == item.length; } public void push(T e) // Pushes elem e on the stack { if ( isFull () ) { System.out.println("Full"); return ; } item[ stackTop ] = e; stackTop++; } public T pop() // Remove the elem at the top { if ( isEmpty() ) { System.out.println("Empty"); return null; } stackTop--; return item[ stackTop ]; } public T peek() // Return the elem at the top { if ( isEmpty() ) { System.out.println("Empty"); return null; } else return item[ stackTop-1 ]; } @Override public String toString() { String s = ">>> "; for ( int i = 0; i < stackTop; i++ ) s += item[i] + " "; return s; } }