Stack ADT Specification
The Stack interface does not say what pop should do when the stack is empty, or whether push accepts null. Let’s add these specifications to interface to clarify the contract of the stack ADT.
/**
* A Stack is a collection that supports last-in-first-out (LIFO) access.
* @param <T> the type of elements in this stack
*/
public interface Stack<T> {
/**
* Pushes an item onto the top of this stack.
* @param item the item to be pushed onto this stack
* @throws IllegalArgumentException if the item is null
*/
void push(T item);
/**
* Removes the item at the top of this stack.
* @throws NoSuchElementException if this stack is empty
*/
void pop();
/**
* Returns the item at the top of this stack without removing it.
* @return the item at the top of this stack
* @throws NoSuchElementException if this stack is empty
*/
T top();
/**
* Returns true if this stack contains no elements.
* @return true if this stack is empty, false otherwise
*/
boolean isEmpty();
}
On an empty stack, pop and top throw a NoSuchElementException. (There is no index involved, so the IndexOutOfBoundsException we used for List would not fit here.) The push method also rejects null, throwing an IllegalArgumentException.
You can find a suite of tests for this interface in the StackTest class within the code accompanying this chapter that further clarifies the expected behavior of the stack ADT.