Section 5.1. Legacy Library with Legacy Client


5.1. Legacy Library with Legacy Client

We begin with a simple library of stacks and an associated client, as presented in Example 5.1. This is legacy code, written for Java 1.4 and its version of the Collections Framework. Like the Collections Framework, we structure the library as an interface Stack (analogous to List), an implementation class ArrayStack (analogous to ArrayList), and a utility class Stacks (analogous to Collections). The interface Stack provides just three methods: empty, push, and pop. The implementation class ArrayStack provides a single constructor with no arguments, and implements the methods empty, push, and pop using methods size, add, and remove on lists. The body of pop could be shorterinstead of assigning the value to the variable, it could be returned directlybut it will be interesting to see how the type of the variable changes as the code evolves. The utility class provides just one method, reverse, which repeatedly pops from one stack and pushes onto another.

Example 5-1. Legacy library with legacy client

 l/Stack.java:   interface Stack {     public boolean empty();     public void push(Object elt);     public Object pop();   } l/ArrayStack.java:   import java.util.*;   class ArrayStack implements Stack {     private List list;     public ArrayStack() { list = new ArrayList(); }     public boolean empty() { return list.size() == 0; }     public void push(Object elt) { list.add(elt); }     public Object pop() {       Object elt = list.remove(list.size()-1);       return elt;     }     public String toString() { return "stack"+list.toString(); }   } l/Stacks.java:   class Stacks {     public static Stack reverse(Stack in) {       Stack out = new ArrayStack();       while (!in.empty()) {         Object elt = in.pop();         out.push(elt);       }       return out;     }   } l/Client.java:   class Client {     public static void main(String[]  args) {       Stack stack = new ArrayStack();       for (int i = 0; i<4; i++) stack.push(new Integer(i));       assert stack.toString().equals("stack[0, 1, 2, 3]");       int top = ((Integer)stack.pop()).intValue();       assert top == 3 && stack.toString().equals("stack[0, 1, 2]");       Stack reverse = Stacks.reverse(stack);       assert stack.empty();       assert reverse.toString().equals("stack[2, 1, 0]");     }   } 

The client allocates a stack, pushes a few integers onto it, pops an integer off, and then reverses the remainder into a fresh stack. Since this is Java 1.4, integers must be explicitly boxed when passed to push, and explicitly unboxed when returned by pop.




Java Generics and Collections
Java Generics and Collections
ISBN: 0596527756
EAN: 2147483647
Year: 2006
Pages: 136

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net