CS/SWE 332 In Class Exercise Number 26
November 29, 2017


This is a solo in-class exercise based on quiz 12. If you really understand this exercise, quiz 13 ought to be a breeze.

Here's a generic variant of Bloch's Stack example:

public class MyStack <E> {
   private List<E> elements;

   public MyStack() { this.elements = new ArrayList<E>(); }

   public void push (E e) {
     if (e == null) throw new NullPointerException("MyStack.push");

   public boolean isEmpty () { return elements.size() == 0; }

   public E pop () {
     if (isEmpty()) throw new IllegalArgumentException("MyStack.pop");
     return elements.remove(elements.size()-1);

   // pop entire (and possibly already empty) stack into collection c
   public void popAll(Collection<E> c) {
     while (!isEmpty()) { c.add(pop()); }

  1. What invariant about the contents of elements is true for the given code?
    How do the invariants differ between this implementation and Bloch's original implementation?
    What happens to the invariant if we add the private variable size back in?

  2. Should pop() throw an exception?
    If not, why not?
    If so, what are reasonable exceptions for pop()? Are there unreasonable exceptions? If so, list some.
    Write a JavaDoc contract for pop().
    How would you argue that pop() is correct?

  3. As Stack is written, pop() requires special documention?
    Why? Write code that demonstrates the issue.
    What change to the code of pop() itself removes the need for this documentation?
    What change(s) to the code (OTHER THAN to pop()) removes the need for this documentation?

  4. What generic parameter is preferable to E in popAll()?
    Write client code that takes advantate of this change.
    What if popAll() returned a (new) collection instead of modifying an argument. What is the best type for the collection in this case?
    Would it be possible to simply return the elements list? Why or why not?

  5. Does Bloch's standard recipe for equals() in Stack and satisfy its contract?
    If equals() is overridden, what else would Bloch do, and how?
    Are there issues with subtypes of Stack and equals()? If so, how would Bloch recommend handling that?

  6. Suppose we implement clone()\ in Stack. What are the likely ways to get it wrong, and how does Bloch recommend avoiding these errors?