Java8源码-Stack

学完了ArrayListVectorLinkedList的源码后,今天来学习Stack源码。参考的JDK版本为1.8。

Stack继承了Vector,学习了Vector再来学习Stack就变得很简单。Stack,栈,特点是先进后出(FILO, First In Last Out)。Stack是如何实现先进后出的?本文将详细讲解这个问题。

顶部注释

The Stack class represents a last-in-first-out (LIFO) stack of objects. It extends class Vector with five operations that allow a vector to be treated as a stack. The usual push and pop operations are provided, as well as a method to peek at the top item on the stack, a method to test for whether the stack is empty, and a method to search the stack for an item and discover how far it is from the top.

第一段大意为Stack是last-in-first-out (LIFO) 的。它继承Vector,并额外提供了push、pop、peek、empty、search这几个方法。

When a stack is first created, it contains no items.

第二段大意为当stack被第一次创建时,它包含0个元素。

A more complete and consistent set of LIFO stack operations is provided by the {@link Deque} interface and its implementations,

Deque<Integer> stack = new ArrayDeque<Integer>();

第三段大意为Deque接口和它的实现是更强大的先进先出的栈的实现。

Stack类层次结构

先来看看Stack的定义

public class Stack<E> extends Vector<E>

从中我们可以了解到

  • Stack<E>:说明它支持泛型。
  • extends Vector<<E>`:说明Vector的可序列化、随机访问效率高等等特性它都有。

下图是Stack的类结构层次图

如何查看类层次结构图可以参考我写过的一篇文章:

eclipse-查看继承层次图/继承实现层次图

全局变量

Stack的全局变量都是从Vector继承的。

构造方法

接下来,看Stack提供的构造方法。ArrayList提供了一种构造方法。

1.构造空Stack。

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

方法

public E push( E item)
/**
 * 添加元素的到栈顶。
 *
 * @param   item  要添加的元素
 * @return  被添加的元素
 * @see     java.util.Vector#addElement
 */
public E push(E item) {
    addElement(item);

    return item;
}
public synchronized E pop()
/**
 * 返回栈顶元素,并将其从栈中删除
 *
 * @return  栈顶元素
 * @throws  EmptyStackException 如果栈为空
 */
public synchronized E pop() {
    E obj;
    int len = size();

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

    return obj;
}
peek()
/**
 * 返回栈顶元素,不删除。
 *
 * @return  栈顶元素
 * @throws  EmptyStackException  如果栈为空
 */
public synchronized E peek() {
    int len = size();

    if (len == 0)
        throw new EmptyStackException();
    return elementAt(len - 1);
}
empty()
/**
 * 判断栈是否为空
 *
 * @return  栈是否有元素
 */
public boolean empty() {
    return size() == 0;
}
search(Object)
/**
 * 栈底向栈顶方向遍历,查找指定对象o在栈中的位置。
 * @param   o   指定对象
 * @return  o的索引,如果没找到,返回-1
 */
public synchronized int search(Object o) {
    int i = lastIndexOf(o);

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

Stack的学习就到这里了,List的学习到这里也告一段落了,下一篇文章将对List的各个实现类做总结。

本文已收录于Java8容器源码札记专栏

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值