Java集合框架06-Stack

第1部分 Stack介绍

Stack简介

Stack是栈。它的特性是:先进后出(FILO, First In Last Out)。

java工具包中的Stack是继承于Vector(矢量队列)的,由于Vector是通过数组实现的,这就意味着,Stack也是通过数组实现的而非链表。当然,我们也可以将LinkedList当作栈来使用!

Stack的继承关系

java.lang.Object
↳     java.util.AbstractCollection<E>
   ↳     java.util.AbstractList<E>
       ↳     java.util.Vector<E>
           ↳     java.util.Stack<E>

public class Stack<E> extends Vector<E> {}

第2部分 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的可序列化、随机访问效率高等等特性它都有。

 

/**
 * 构造方法
 */
public Stack() {
}

// 添加元素到栈顶
public E push(E item) {
   addElement(item);

   return item;
}

// 返回栈顶元素,并将其从栈中删除
    public synchronized E pop() {
        E       obj;
        int     len = size();

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

        return obj;
    }

// 返回栈顶元素,不删除。
    public synchronized E peek() {
        int     len = size();

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

// 判断栈是否为空
public boolean empty() {
        return size() == 0;
    }

// 栈底向栈顶方向遍历,查找指定对象o在栈中的位置。
    public synchronized int search(Object o) {
        int i = lastIndexOf(o);

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

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值