Source of Stack.java


  1: // Fig. 18.7: Stack.java
  2: // Generic class Stack.
  3: 
  4: public class Stack< E >  
  5: {
  6:    private final int size; // number of elements in the stack
  7:    private int top; // location of the top element
  8:    private E[] elements; // array that stores stack elements
  9: 
 10:    // no-argument constructor creates a stack of the default size
 11:    public Stack()
 12:    {
 13:       this( 10 ); // default stack size
 14:    } // end no-argument Stack constructor
 15:    
 16:    // constructor creates a stack of the specified number of elements
 17:    public Stack( int s )
 18:    {
 19:       size = s > 0 ? s : 10; // set size of Stack
 20:       top = -1; // Stack initially empty
 21: 
 22:       elements = ( E[] ) new Object[ size ]; // create array 
 23:    } // end one-argument Stack constructor
 24: 
 25:    // push element onto stack; if successful, return true; 
 26:    // otherwise, throw FullStackException
 27:    public void push( E pushValue )
 28:    {
 29:       if ( top == size - 1 ) // if stack is full
 30:          throw new FullStackException( String.format( 
 31:             "Stack is full, cannot push %s", pushValue ) );
 32: 
 33:       elements[ ++top ] = pushValue; // place pushValue on Stack
 34:    } // end method push
 35: 
 36:    // return the top element if not empty; else throw EmptyStackException
 37:    public E pop()
 38:    {
 39:       if ( top == -1 ) // if stack is empty
 40:          throw new EmptyStackException( "Stack is empty, cannot pop" );
 41: 
 42:       return elements[ top-- ]; // remove and return top element of Stack
 43:    } // end method pop
 44: } // end class Stack< E >
 45: 
 46: /**************************************************************************
 47:  * (C) Copyright 1992-2005 by Deitel & Associates, Inc. and               *
 48:  * Pearson Education, Inc. All Rights Reserved.                           *
 49:  *                                                                        *
 50:  * DISCLAIMER: The authors and publisher of this book have used their     *
 51:  * best efforts in preparing the book. These efforts include the          *
 52:  * development, research, and testing of the theories and programs        *
 53:  * to determine their effectiveness. The authors and publisher make       *
 54:  * no warranty of any kind, expressed or implied, with regard to these    *
 55:  * programs or to the documentation contained in these books. The authors *
 56:  * and publisher shall not be liable in any event for incidental or       *
 57:  * consequential damages in connection with, or arising out of, the       *
 58:  * furnishing, performance, or use of these programs.                     *
 59:  *************************************************************************/