java源码剖析之Stack

/**
 * The <code>Stack</code> class represents a last-in-first-out
 * (LIFO) stack of objects. It extends class <tt>Vector</tt> with five
 * operations that allow a vector to be treated as a stack. The usual
 * <tt>push</tt> and <tt>pop</tt> operations are provided, as well as a
 * method to <tt>peek</tt> at the top item on the stack, a method to test
 * for whether the stack is <tt>empty</tt>, and a method to <tt>search</tt>
 * the stack for an item and discover how far it is from the top.
 * <p>
 * When a stack is first created, it contains no items.
 *
 * <p>A more complete and consistent set of LIFO stack operations is
 * provided by the {@link Deque} interface and its implementations, which
 * should be used in preference to this class.  For example:
 * <pre>   {@code
 *   Deque<Integer> stack = new ArrayDeque<Integer>();}</pre>
 *
 * @author  Jonathan Payne
 * @since   JDK1.0
 */


翻译如下:

栈是一个后进先出的数据结构,它是vector的子类,并且只有五种操作。分别是push,pop,peek,还有一个返回stack是否为空的方法:empty,最后一个方法是search,此方法是用于查询元素并且返回一个整型数代表此元素距离栈顶的距离。

 

/**
     * Creates an empty Stack.
     */
    public Stack() {
    }


注解:只有一个构造函数,创建空栈

 public E push(E item) {
        addElement(item);

        return item;
    }


注解:元素进栈,使用的vector类的addElement方法,并且返回进栈元素

public synchronized E pop() {
        E       obj;
        int     len = size();

        obj = peek();
        removeElementAt(len - 1);

        return obj;
    }


注解:移除栈顶元素,首先使用的peek方法,获取栈顶元素值,然后使用的vector类的removeElementAt方法删除栈顶值。最后返回栈顶值(需要注意的是此方法是安全的)

 public synchronized E peek() {
        int     len = size();

        if (len == 0)
            throw new EmptyStackException();
        return elementAt(len - 1);
    }

注解:返回栈顶元素。首先判断是否有元素存在,如果不存在即抛出空栈异常,否则直接调用父类的elementAt方法,返回栈顶元素。(这个方法也是同步安全的)

 public boolean empty() {
        return size() == 0;
    }

注解:检查此栈是否为空

public synchronized int search(Object o) {
        int i = lastIndexOf(o);

        if (i >= 0) {
            return size() - i;
        }
        return -1;
    }

注解:返回参数距离栈顶的距离。首先是用父类的lastIndexOf方法,获取参数最后一次出现的位置,然后用栈的大小减去这个位置即可,如果元素不存在,则返回-1。(同步方法)

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Narasimha_Karumanchi

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值