Java 集合框架之 Stack

Java 集合框架之 Stack

简介

java.util.Stack降生于jdk1.0

继承自java.util.Vector,所以从jdk1.2开始,也是集合框架中的一员,归属于List这个子类。

这个类已经不太推荐使用,优先使用java.util.Deque的实现。
优先使用java.util.Deque的原因:

  1. 因为这个类是java.util.Vector,而且拓展的几个方法也是线程安全的,所以这个类是线程安全的,都是性能也会相对较差。
  2. 接口没有java.util.Deque完善
  3. 各种设计感觉有缺陷:java.util.Vector

源码解析

源码基于JDK 1.8u201

由于java.util.Stack中的方法基于java.util.Vector,这篇文章不做详细解说,详情查看 Vector 源码解析

入栈 todo

    /**
     * Pushes an item onto the top of this stack. This has exactly
     * the same effect as:
     * <blockquote><pre>
     * addElement(item)</pre></blockquote>
     *
     * @param   item   the item to be pushed onto this stack.
     * @return  the <code>item</code> argument.
     * @see     java.util.Vector#addElement
     */
    public E push(E item) {
        addElement(item);

        return item;
    }

入栈操作是将元素插入到尾端。

出栈 todo

    /**
     * Removes the object at the top of this stack and returns that
     * object as the value of this function.
     *
     * @return  The object at the top of this stack (the last item
     *          of the <tt>Vector</tt> object).
     * @throws  EmptyStackException  if this stack is empty.
     */
    public synchronized E pop() {
        E       obj;
        int     len = size();

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

        return obj;
    }

出栈操作是读取尾端元素,然后移除。

查看栈顶元素

    /**
     * Looks at the object at the top of this stack without removing it
     * from the stack.
     *
     * @return  the object at the top of this stack (the last item
     *          of the <tt>Vector</tt> object).
     * @throws  EmptyStackException  if this stack is empty.
     */
    public synchronized E peek() {
        int     len = size();

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

这个方法只是查看尾端元素,而不移除。
需要注意的是:如果为空栈时,会抛出java.util.EmptyStackException异常,所以记得先判断是否为空栈或者捕捉异常。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值