home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 1997 May / Pcwk0597.iso / sybase / starbuck / java.z / Stack.java < prev    next >
Text File  |  1996-05-03  |  2KB  |  87 lines

  1. /*
  2.  * @(#)Stack.java    1.12 95/08/11  
  3.  *
  4.  * Copyright (c) 1994 Sun Microsystems, Inc. All Rights Reserved.
  5.  *
  6.  * Permission to use, copy, modify, and distribute this software
  7.  * and its documentation for NON-COMMERCIAL purposes and without
  8.  * fee is hereby granted provided that this copyright notice
  9.  * appears in all copies. Please refer to the file "copyright.html"
  10.  * for further important copyright and licensing information.
  11.  *
  12.  * SUN MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF
  13.  * THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
  14.  * TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
  15.  * PARTICULAR PURPOSE, OR NON-INFRINGEMENT. SUN SHALL NOT BE LIABLE FOR
  16.  * ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR
  17.  * DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.
  18.  */
  19.  
  20. package java.util;
  21.  
  22. /**
  23.  * A Last-In-First-Out(LIFO) stack of objects.
  24.  *
  25.  * @version     1.12, 11 Aug 1995
  26.  * @author     Jonathan Payne
  27.  */
  28. public
  29. class Stack extends Vector {
  30.     /**
  31.      * Pushes an item onto the stack.
  32.      * @param item the item to be pushed on.
  33.      */
  34.     public Object push(Object item) {
  35.     addElement(item);
  36.  
  37.     return item;
  38.     }
  39.  
  40.     /**
  41.      * Pops an item off the stack.
  42.      * @exception EmptyStackException If the stack is empty.
  43.      */
  44.     public Object pop() {
  45.     Object    obj;
  46.     int    len = size();
  47.  
  48.     obj = peek();
  49.     removeElementAt(len - 1);
  50.  
  51.     return obj;
  52.     }
  53.  
  54.     /**
  55.      * Peeks at the top of the stack.
  56.      * @exception EmptyStackException If the stack is empty.
  57.      */
  58.     public Object peek() {
  59.     int    len = size();
  60.  
  61.     if (len == 0)
  62.         throw new EmptyStackException();
  63.     return elementAt(len - 1);
  64.     }
  65.  
  66.     /**
  67.      * Returns true if the stack is empty.
  68.      */
  69.     public boolean empty() {
  70.     return size() == 0;
  71.     }
  72.  
  73.     /**
  74.      * Sees if an object is on the stack.
  75.      * @param o the desired object
  76.      * @return the distance from the top, or -1 if it is not found.
  77.      */
  78.     public int search(Object o) {
  79.     int i = lastIndexOf(o);
  80.  
  81.     if (i >= 0) {
  82.         return size() - i;
  83.     }
  84.     return -1;
  85.     }
  86. }
  87.