001    /*
002      Copyright (C) 2001 Laurent Martelli
003    
004      This program is free software; you can redistribute it and/or modify
005      it under the terms of the GNU Lesser General Public License as
006      published by the Free Software Foundation; either version 2 of the
007      License, or (at your option) any later version.
008    
009      This program is distributed in the hope that it will be useful,
010      but WITHOUT ANY WARRANTY; without even the implied warranty of
011      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
012      GNU Lesser General Public License for more details.
013    
014      You should have received a copy of the GNU Lesser General Public License
015      along with this program; if not, write to the Free Software
016      Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */
017    
018    package org.objectweb.jac.util;
019    
020    public class Stack extends java.util.Stack {
021        /**
022         * Returns the i-th element from the top of the stack
023         *
024         * @param i index of element to get (0 is the top of the stack,
025         * size()-1 is the bottom)
026         *
027         * @see #poke(int,Object)
028         * @see #top()
029         */
030        public Object peek(int i) {
031            return get(size()-1-i);
032        }
033    
034        /**
035         * Returns the top element of the stack
036         */
037        public Object top() {
038            return peek(0);
039        }
040    
041        /**
042         * Returns the top element of the stack if it's not empty, null
043         * otherwise.
044         */
045        public Object safeTop() {
046            return empty()?null:peek(0);
047        }
048    
049        /**
050         * Sets the value of an element of the stack
051         *
052         * @param i index of element to set (0 is the top of the stack,
053         * size()-1 is the bottom)
054         * @param value the new value
055         *
056         * @see #peek(int)
057         */
058        public void poke(int i, Object value) {
059            set(size()-1-i,value);
060        }
061        /**
062        * Pops n elements from the top of the stack
063        * @param n number of elements to pop off the stack
064        */
065        public void pop(int n) {
066            for (;n>0; n--) {
067                pop();
068            }
069        }
070        /**
071        * swap peek() and peek(1)
072        */
073        public void swap() {
074            Object tmp = peek();
075            poke(0,peek(1));
076            poke(1,tmp);
077        }
078    }