SWE/CS 332 In Class Exercise # 7
September 20, 2017


Name(s):

Consider Bloch's Stack class:
public class Stack {

   private Object[] elements;
   private int size = 0;
   private final int DEFAULT_CAPACITY = 10;


   public Stack() {
     this.elements = new Object[DEFAULT_CAPACITY];
   }

   public void push (Object e) {
     ensureCapacity();
     elements[size++] = e;
   }

   public Object pop () {
     if (size == 0) throw new IllegalStateException("Stack.pop");
     Object result = elements[--size];
     elements[size] = null;
     return result;
   }

   private void ensureCapacity() {
      if (elements.length == size) {
         Object oldElements[] = elements;
         elements = new Object[2*size + 1];
         System.arraycopy(oldElements, 0, elements, 0, size);
      }
   }

}
Code an immutable version. Keep the same instance variables. Follow Liskov's guidance for immutability. We'll get to Bloch's rules later. Specific items: What happens to:
  1. the constructor implementation?
  2. DEFAULT_CAPACITY?
  3. push()?
  4. pop()?
  5. ensureCapacity()?
What is a better representation for an immutable stack?