Java Reference
In-Depth Information
5.3
The Java interface in Listing 5-1 specifies a stack of objects. The generic type T —which represents
any class type—is the data type of the items in the stack.
LISTING 5-1
An interface for the ADT stack
public interface StackInterface<T>
{
/** Adds a new entry to the top of this stack.
@param newEntry an object to be added to the stack */
public void push(T newEntry);
/** Removes and returns this stack's top entry.
@return either the object at the top of the stack or, if the
stack is empty before the operation, null */
public T pop();
/** Retrieves this stack's top entry.
@return either the object at the top of the stack or null if
the stack is empty */
public T peek();
/** Detects whether this stack is empty.
@return true if the stack is empty */
public boolean isEmpty();
/** Removes all entries from this stack */
public void clear();
} // end StackInterface
5.4
Example: Demonstrating the stack methods. The following statements add, retrieve, and remove
strings from a stack. We assume that the class OurStack implements StackInterface and is avail-
able for our use.
StackInterface<String> stringStack = new OurStack<String>();
stringStack.push("Jim");
stringStack.push("Jess");
stringStack.push("Jill");
stringStack.push("Jane");
stringStack.push("Joe");
String top = stringStack.peek(); // returns "Joe"
System.out.println(top + " is at the top of the stack.");
top = stringStack.pop(); // removes and returns "Joe"
System.out.println(top + " is removed from the stack.");
top = stringStack.peek(); // returns "Jane"
System.out.println(top + " is at the top of the stack.");
 
Search WWH ::




Custom Search