Java examples for Object Oriented Design:Generic Class
Raw type test program.
import java.util.ArrayList; class EmptyStackException extends RuntimeException { // no-argument constructor public EmptyStackException() {//from ww w. j a v a2 s. c o m this("Stack is empty"); } // one-argument constructor public EmptyStackException(String exception) { super(exception); } } class Stack<T> { private final ArrayList<T> elements; // ArrayList stores stack elements // no-argument constructor creates a stack of the default size public Stack() { this(10); // default stack size } // constructor creates a stack of the specified number of elements public Stack(int capacity) { int initCapacity = capacity > 0 ? capacity : 10; // validate elements = new ArrayList<T>(initCapacity); // create ArrayList } // push element onto stack public void push(T pushValue) { elements.add(pushValue); // place pushValue on Stack } // return the top element if not empty; else throw EmptyStackException public T pop() { if (elements.isEmpty()) // if stack is empty throw new EmptyStackException("Stack is empty, cannot pop"); // remove and return top element of Stack return elements.remove(elements.size() - 1); } } public class Main { public static void main(String[] args) { Double[] doubleElements = {1.1, 2.2, 3.3, 4.4, 5.5}; Integer[] integerElements = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; // Stack of raw types assigned to Stack of raw types variable Stack rawTypeStack1 = new Stack(5); // Stack<Double> assigned to Stack of raw types variable Stack rawTypeStack2 = new Stack<Double>(5); // Stack of raw types assigned to Stack<Integer> variable Stack<Integer> integerStack = new Stack(10); testPush("rawTypeStack1", rawTypeStack1, doubleElements); testPop("rawTypeStack1", rawTypeStack1); testPush("rawTypeStack2", rawTypeStack2, doubleElements); testPop("rawTypeStack2", rawTypeStack2); testPush("integerStack", integerStack, integerElements); testPop("integerStack", integerStack); } // generic method pushes elements onto stack private static <T> void testPush(String name, Stack<T> stack, T[] elements) { System.out.printf("%nPushing elements onto %s%n", name); // push elements onto Stack for (T element : elements) { System.out.printf("%s ", element); stack.push(element); // push element onto stack } } // generic method testPop pops elements from stack private static <T> void testPop(String name, Stack<T> stack) { // pop elements from stack try { System.out.printf("%nPopping elements from %s%n", name); T popValue; // store element removed from stack // remove elements from Stack while (true) { popValue = stack.pop(); // pop from stack System.out.printf("%s ", popValue); } } catch(EmptyStackException emptyStackException) { System.out.println(); emptyStackException.printStackTrace(); } } }