// This is how a class is defined to take in objects of // so-called generic types. That is, the class definition // uses a generic type (that we call StackDataType). At compile time, // MyStack can be compiled without knowing what types will actually // be used. class MyStack { // This is now an array of the generic type. StackDataType [] stack; int stackTop; public void initialize () { // Arrays of generic types cannot be instantiated directly // in Java. This is the workaround. stack = (StackDataType[]) new Object [100]; } // Note: the parameter is now of the generic type. public void push (StackDataType value) { stack[++stackTop] = value; } // Note: the return value is now of the generic type. public StackDataType pop () { StackDataType value = stack[stackTop]; stackTop --; return value; } public boolean isEmpty () { if (stackTop < 0) { return true; } else { return false; } } } public class StackExample4 { public static void main (String[] argv) { // Now MyStack can be defined to accept only String's. MyStack stack = new MyStack (); stack.initialize (); stack.push ("Alice"); stack.push ("Bob"); stack.push ("Chen"); while (! stack.isEmpty ()) { // No cast required. String name = stack.pop (); System.out.println ("Removed " + name); } } }