类继承树如下图:

一、Java中的栈 Stack

Stack是一个后进先出(last in first out,LIFO)的堆栈,在Vector类的基础上,扩展了5个方法

1、Stack类源码

package java.util;
/** * 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 */
public class Stack<E> extends Vector<E> { 
    /** * Creates an empty Stack. */
    public Stack() { 
    }

    /** * 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;
    }

    /** * 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);
    }

    /** * Tests if this stack is empty. * * @return <code>true</code> if and only if this stack contains * no items; <code>false</code> otherwise. */
    public boolean empty() { 
        return size() == 0;
    }

    /** * Returns the 1-based position where an object is on this stack. * If the object <tt>o</tt> occurs as an item in this stack, this * method returns the distance from the top of the stack of the * occurrence nearest the top of the stack; the topmost item on the * stack is considered to be at distance <tt>1</tt>. The <tt>equals</tt> * method is used to compare <tt>o</tt> to the * items in this stack. * * @param o the desired object. * @return the 1-based position from the top of the stack where * the object is located; the return value <code>-1</code> * indicates that the object is not on the stack. */
    public synchronized int search(Object o) { 
        int i = lastIndexOf(o);

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

    /** use serialVersionUID from JDK 1.0.2 for interoperability */
    private static final long serialVersionUID = 1224463164541339165L;
}

2、方法说明

方法 说明
E push(E item) 把item推入堆栈顶部
E pop() 推出堆栈顶部对象,并返回该对象
E peek() 返回堆栈顶部的对象,不对其做任何操作
boolean empty() 测试堆栈是否为空
int search(Object o) 返回o在堆栈中的位置,从1开始

3、Stack用法

Stack stack=new Stack();
Stack<Integer> st = new Stack<Integer>();

4、目前官方已不推荐使用Stack,而推荐java.util.Deque

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

在Stack源码中已有体现

Deque(双端队列)比起Stack具有更好的完整性和一致性

二、JAVA中的栈Deque

1、Deque类源码

/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */
/* * This file is available under and governed by the GNU General Public * License version 2 only, as published by the Free Software Foundation. * However, the following notice accompanied the original version of this * file: * * Written by Doug Lea and Josh Bloch with assistance from members of * JCP JSR-166 Expert Group and released to the public domain, as explained * at http://creativecommons.org/publicdomain/zero/1.0/ */
package java.util;
// Android-changed: removed link to collections framework docs
/** * A linear collection that supports element insertion and removal at * both ends. The name <i>deque</i> is short for "double ended queue" * and is usually pronounced "deck". Most {@code Deque} * implementations place no fixed limits on the number of elements * they may contain, but this interface supports capacity-restricted * deques as well as those with no fixed size limit. * * <p>This interface defines methods to access the elements at both * ends of the deque. Methods are provided to insert, remove, and * examine the element. Each of these methods exists in two forms: * one throws an exception if the operation fails, the other returns a * special value (either {@code null} or {@code false}, depending on * the operation). The latter form of the insert operation is * designed specifically for use with capacity-restricted * {@code Deque} implementations; in most implementations, insert * operations cannot fail. * * <p>The twelve methods described above are summarized in the * following table: * * <table BORDER CELLPADDING=3 CELLSPACING=1> * <caption>Summary of Deque methods</caption> * <tr> * <td></td> * <td ALIGN=CENTER COLSPAN = 2> <b>First Element (Head)</b></td> * <td ALIGN=CENTER COLSPAN = 2> <b>Last Element (Tail)</b></td> * </tr> * <tr> * <td></td> * <td ALIGN=CENTER><em>Throws exception</em></td> * <td ALIGN=CENTER><em>Special value</em></td> * <td ALIGN=CENTER><em>Throws exception</em></td> * <td ALIGN=CENTER><em>Special value</em></td> * </tr> * <tr> * <td><b>Insert</b></td> * <td>{@link Deque#addFirst addFirst(e)}</td> * <td>{@link Deque#offerFirst offerFirst(e)}</td> * <td>{@link Deque#addLast addLast(e)}</td> * <td>{@link Deque#offerLast offerLast(e)}</td> * </tr> * <tr> * <td><b>Remove</b></td> * <td>{@link Deque#removeFirst removeFirst()}</td> * <td>{@link Deque#pollFirst pollFirst()}</td> * <td>{@link Deque#removeLast removeLast()}</td> * <td>{@link Deque#pollLast pollLast()}</td> * </tr> * <tr> * <td><b>Examine</b></td> * <td>{@link Deque#getFirst getFirst()}</td> * <td>{@link Deque#peekFirst peekFirst()}</td> * <td>{@link Deque#getLast getLast()}</td> * <td>{@link Deque#peekLast peekLast()}</td> * </tr> * </table> * * <p>This interface extends the {@link Queue} interface. When a deque is * used as a queue, FIFO (First-In-First-Out) behavior results. Elements are * added at the end of the deque and removed from the beginning. The methods * inherited from the {@code Queue} interface are precisely equivalent to * {@code Deque} methods as indicated in the following table: * * <table BORDER CELLPADDING=3 CELLSPACING=1> * <caption>Comparison of Queue and Deque methods</caption> * <tr> * <td ALIGN=CENTER> <b>{@code Queue} Method</b></td> * <td ALIGN=CENTER> <b>Equivalent {@code Deque} Method</b></td> * </tr> * <tr> * <td>{@link java.util.Queue#add add(e)}</td> * <td>{@link #addLast addLast(e)}</td> * </tr> * <tr> * <td>{@link java.util.Queue#offer offer(e)}</td> * <td>{@link #offerLast offerLast(e)}</td> * </tr> * <tr> * <td>{@link java.util.Queue#remove remove()}</td> * <td>{@link #removeFirst removeFirst()}</td> * </tr> * <tr> * <td>{@link java.util.Queue#poll poll()}</td> * <td>{@link #pollFirst pollFirst()}</td> * </tr> * <tr> * <td>{@link java.util.Queue#element element()}</td> * <td>{@link #getFirst getFirst()}</td> * </tr> * <tr> * <td>{@link java.util.Queue#peek peek()}</td> * <td>{@link #peek peekFirst()}</td> * </tr> * </table> * * <p>Deques can also be used as LIFO (Last-In-First-Out) stacks. This * interface should be used in preference to the legacy {@link Stack} class. * When a deque is used as a stack, elements are pushed and popped from the * beginning of the deque. Stack methods are precisely equivalent to * {@code Deque} methods as indicated in the table below: * * <table BORDER CELLPADDING=3 CELLSPACING=1> * <caption>Comparison of Stack and Deque methods</caption> * <tr> * <td ALIGN=CENTER> <b>Stack Method</b></td> * <td ALIGN=CENTER> <b>Equivalent {@code Deque} Method</b></td> * </tr> * <tr> * <td>{@link #push push(e)}</td> * <td>{@link #addFirst addFirst(e)}</td> * </tr> * <tr> * <td>{@link #pop pop()}</td> * <td>{@link #removeFirst removeFirst()}</td> * </tr> * <tr> * <td>{@link #peek peek()}</td> * <td>{@link #peekFirst peekFirst()}</td> * </tr> * </table> * * <p>Note that the {@link #peek peek} method works equally well when * a deque is used as a queue or a stack; in either case, elements are * drawn from the beginning of the deque. * * <p>This interface provides two methods to remove interior * elements, {@link #removeFirstOccurrence removeFirstOccurrence} and * {@link #removeLastOccurrence removeLastOccurrence}. * * <p>Unlike the {@link List} interface, this interface does not * provide support for indexed access to elements. * * <p>While {@code Deque} implementations are not strictly required * to prohibit the insertion of null elements, they are strongly * encouraged to do so. Users of any {@code Deque} implementations * that do allow null elements are strongly encouraged <i>not</i> to * take advantage of the ability to insert nulls. This is so because * {@code null} is used as a special return value by various methods * to indicated that the deque is empty. * * <p>{@code Deque} implementations generally do not define * element-based versions of the {@code equals} and {@code hashCode} * methods, but instead inherit the identity-based versions from class * {@code Object}. * * @author Doug Lea * @author Josh Bloch * @since 1.6 * @param <E> the type of elements held in this deque */
// Android-changed: fix framework docs link to "Collection#optional-restrictions"
// Several occurrences of the link have been fixed throughout.
public interface Deque<E> extends Queue<E> { 
/** * Inserts the specified element at the front of this deque if it is * possible to do so immediately without violating capacity restrictions, * throwing an {@code IllegalStateException} if no space is currently * available. When using a capacity-restricted deque, it is generally * preferable to use method {@link #offerFirst}. * * @param e the element to add * @throws IllegalStateException if the element cannot be added at this * time due to capacity restrictions * @throws ClassCastException if the class of the specified element * prevents it from being added to this deque * @throws NullPointerException if the specified element is null and this * deque does not permit null elements * @throws IllegalArgumentException if some property of the specified * element prevents it from being added to this deque */
void addFirst(E e);
/** * Inserts the specified element at the end of this deque if it is * possible to do so immediately without violating capacity restrictions, * throwing an {@code IllegalStateException} if no space is currently * available. When using a capacity-restricted deque, it is generally * preferable to use method {@link #offerLast}. * * <p>This method is equivalent to {@link #add}. * * @param e the element to add * @throws IllegalStateException if the element cannot be added at this * time due to capacity restrictions * @throws ClassCastException if the class of the specified element * prevents it from being added to this deque * @throws NullPointerException if the specified element is null and this * deque does not permit null elements * @throws IllegalArgumentException if some property of the specified * element prevents it from being added to this deque */
void addLast(E e);
/** * Inserts the specified element at the front of this deque unless it would * violate capacity restrictions. When using a capacity-restricted deque, * this method is generally preferable to the {@link #addFirst} method, * which can fail to insert an element only by throwing an exception. * * @param e the element to add * @return {@code true} if the element was added to this deque, else * {@code false} * @throws ClassCastException if the class of the specified element * prevents it from being added to this deque * @throws NullPointerException if the specified element is null and this * deque does not permit null elements * @throws IllegalArgumentException if some property of the specified * element prevents it from being added to this deque */
boolean offerFirst(E e);
/** * Inserts the specified element at the end of this deque unless it would * violate capacity restrictions. When using a capacity-restricted deque, * this method is generally preferable to the {@link #addLast} method, * which can fail to insert an element only by throwing an exception. * * @param e the element to add * @return {@code true} if the element was added to this deque, else * {@code false} * @throws ClassCastException if the class of the specified element * prevents it from being added to this deque * @throws NullPointerException if the specified element is null and this * deque does not permit null elements * @throws IllegalArgumentException if some property of the specified * element prevents it from being added to this deque */
boolean offerLast(E e);
/** * Retrieves and removes the first element of this deque. This method * differs from {@link #pollFirst pollFirst} only in that it throws an * exception if this deque is empty. * * @return the head of this deque * @throws NoSuchElementException if this deque is empty */
E removeFirst();
/** * Retrieves and removes the last element of this deque. This method * differs from {@link #pollLast pollLast} only in that it throws an * exception if this deque is empty. * * @return the tail of this deque * @throws NoSuchElementException if this deque is empty */
E removeLast();
/** * Retrieves and removes the first element of this deque, * or returns {@code null} if this deque is empty. * * @return the head of this deque, or {@code null} if this deque is empty */
E pollFirst();
/** * Retrieves and removes the last element of this deque, * or returns {@code null} if this deque is empty. * * @return the tail of this deque, or {@code null} if this deque is empty */
E pollLast();
/** * Retrieves, but does not remove, the first element of this deque. * * This method differs from {@link #peekFirst peekFirst} only in that it * throws an exception if this deque is empty. * * @return the head of this deque * @throws NoSuchElementException if this deque is empty */
E getFirst();
/** * Retrieves, but does not remove, the last element of this deque. * This method differs from {@link #peekLast peekLast} only in that it * throws an exception if this deque is empty. * * @return the tail of this deque * @throws NoSuchElementException if this deque is empty */
E getLast();
/** * Retrieves, but does not remove, the first element of this deque, * or returns {@code null} if this deque is empty. * * @return the head of this deque, or {@code null} if this deque is empty */
E peekFirst();
/** * Retrieves, but does not remove, the last element of this deque, * or returns {@code null} if this deque is empty. * * @return the tail of this deque, or {@code null} if this deque is empty */
E peekLast();
/** * Removes the first occurrence of the specified element from this deque. * If the deque does not contain the element, it is unchanged. * More formally, removes the first element {@code e} such that * {@code Objects.equals(o, e)} (if such an element exists). * Returns {@code true} if this deque contained the specified element * (or equivalently, if this deque changed as a result of the call). * * @param o element to be removed from this deque, if present * @return {@code true} if an element was removed as a result of this call * @throws ClassCastException if the class of the specified element * is incompatible with this deque * (<a href="Collection.html#optional-restrictions">optional</a>) * @throws NullPointerException if the specified element is null and this * deque does not permit null elements * (<a href="Collection.html#optional-restrictions">optional</a>) */
boolean removeFirstOccurrence(Object o);
/** * Removes the last occurrence of the specified element from this deque. * If the deque does not contain the element, it is unchanged. * More formally, removes the last element {@code e} such that * {@code Objects.equals(o, e)} (if such an element exists). * Returns {@code true} if this deque contained the specified element * (or equivalently, if this deque changed as a result of the call). * * @param o element to be removed from this deque, if present * @return {@code true} if an element was removed as a result of this call * @throws ClassCastException if the class of the specified element * is incompatible with this deque * (<a href="Collection.html#optional-restrictions">optional</a>) * @throws NullPointerException if the specified element is null and this * deque does not permit null elements * (<a href="Collection.html#optional-restrictions">optional</a>) */
boolean removeLastOccurrence(Object o);
// *** Queue methods ***
/** * Inserts the specified element into the queue represented by this deque * (in other words, at the tail of this deque) if it is possible to do so * immediately without violating capacity restrictions, returning * {@code true} upon success and throwing an * {@code IllegalStateException} if no space is currently available. * When using a capacity-restricted deque, it is generally preferable to * use {@link #offer(Object) offer}. * * <p>This method is equivalent to {@link #addLast}. * * @param e the element to add * @return {@code true} (as specified by {@link Collection#add}) * @throws IllegalStateException if the element cannot be added at this * time due to capacity restrictions * @throws ClassCastException if the class of the specified element * prevents it from being added to this deque * @throws NullPointerException if the specified element is null and this * deque does not permit null elements * @throws IllegalArgumentException if some property of the specified * element prevents it from being added to this deque */
boolean add(E e);
/** * Inserts the specified element into the queue represented by this deque * (in other words, at the tail of this deque) if it is possible to do so * immediately without violating capacity restrictions, returning * {@code true} upon success and {@code false} if no space is currently * available. When using a capacity-restricted deque, this method is * generally preferable to the {@link #add} method, which can fail to * insert an element only by throwing an exception. * * <p>This method is equivalent to {@link #offerLast}. * * @param e the element to add * @return {@code true} if the element was added to this deque, else * {@code false} * @throws ClassCastException if the class of the specified element * prevents it from being added to this deque * @throws NullPointerException if the specified element is null and this * deque does not permit null elements * @throws IllegalArgumentException if some property of the specified * element prevents it from being added to this deque */
boolean offer(E e);
/** * Retrieves and removes the head of the queue represented by this deque * (in other words, the first element of this deque). * This method differs from {@link #poll poll} only in that it throws an * exception if this deque is empty. * * <p>This method is equivalent to {@link #removeFirst()}. * * @return the head of the queue represented by this deque * @throws NoSuchElementException if this deque is empty */
E remove();
/** * Retrieves and removes the head of the queue represented by this deque * (in other words, the first element of this deque), or returns * {@code null} if this deque is empty. * * <p>This method is equivalent to {@link #pollFirst()}. * * @return the first element of this deque, or {@code null} if * this deque is empty */
E poll();
/** * Retrieves, but does not remove, the head of the queue represented by * this deque (in other words, the first element of this deque). * This method differs from {@link #peek peek} only in that it throws an * exception if this deque is empty. * * <p>This method is equivalent to {@link #getFirst()}. * * @return the head of the queue represented by this deque * @throws NoSuchElementException if this deque is empty */
E element();
/** * Retrieves, but does not remove, the head of the queue represented by * this deque (in other words, the first element of this deque), or * returns {@code null} if this deque is empty. * * <p>This method is equivalent to {@link #peekFirst()}. * * @return the head of the queue represented by this deque, or * {@code null} if this deque is empty */
E peek();
// *** Stack methods ***
/** * Pushes an element onto the stack represented by this deque (in other * words, at the head of this deque) if it is possible to do so * immediately without violating capacity restrictions, throwing an * {@code IllegalStateException} if no space is currently available. * * <p>This method is equivalent to {@link #addFirst}. * * @param e the element to push * @throws IllegalStateException if the element cannot be added at this * time due to capacity restrictions * @throws ClassCastException if the class of the specified element * prevents it from being added to this deque * @throws NullPointerException if the specified element is null and this * deque does not permit null elements * @throws IllegalArgumentException if some property of the specified * element prevents it from being added to this deque */
void push(E e);
/** * Pops an element from the stack represented by this deque. In other * words, removes and returns the first element of this deque. * * <p>This method is equivalent to {@link #removeFirst()}. * * @return the element at the front of this deque (which is the top * of the stack represented by this deque) * @throws NoSuchElementException if this deque is empty */
E pop();
// *** Collection methods ***
/** * Removes the first occurrence of the specified element from this deque. * If the deque does not contain the element, it is unchanged. * More formally, removes the first element {@code e} such that * {@code Objects.equals(o, e)} (if such an element exists). * Returns {@code true} if this deque contained the specified element * (or equivalently, if this deque changed as a result of the call). * * <p>This method is equivalent to {@link #removeFirstOccurrence(Object)}. * * @param o element to be removed from this deque, if present * @return {@code true} if an element was removed as a result of this call * @throws ClassCastException if the class of the specified element * is incompatible with this deque * (<a href="Collection.html#optional-restrictions">optional</a>) * @throws NullPointerException if the specified element is null and this * deque does not permit null elements * (<a href="Collection.html#optional-restrictions">optional</a>) */
boolean remove(Object o);
/** * Returns {@code true} if this deque contains the specified element. * More formally, returns {@code true} if and only if this deque contains * at least one element {@code e} such that {@code Objects.equals(o, e)}. * * @param o element whose presence in this deque is to be tested * @return {@code true} if this deque contains the specified element * @throws ClassCastException if the class of the specified element * is incompatible with this deque * (<a href="Collection.html#optional-restrictions">optional</a>) * @throws NullPointerException if the specified element is null and this * deque does not permit null elements * (<a href="Collection.html#optional-restrictions">optional</a>) */
boolean contains(Object o);
/** * Returns the number of elements in this deque. * * @return the number of elements in this deque */
int size();
/** * Returns an iterator over the elements in this deque in proper sequence. * The elements will be returned in order from first (head) to last (tail). * * @return an iterator over the elements in this deque in proper sequence */
Iterator<E> iterator();
/** * Returns an iterator over the elements in this deque in reverse * sequential order. The elements will be returned in order from * last (tail) to first (head). * * @return an iterator over the elements in this deque in reverse * sequence */
Iterator<E> descendingIterator();
}

2、方法说明

方法 说明
addFirst(E e) 添加对象到队首,当超出队列界限的时候,抛出异常
addLast(E e) 添加对象到对尾,当超出队列界限的时候,抛出异常
offerFirst(E e) 添加对象到队首,当超出队列界限的时候,返回false
offerLast(E e) 添加对象到对尾, 当超出队列界限的时候,返回false
E removeFirst() 从对首获取元素并删除,队列为空时,抛出异常
E removeLast() 从队尾获取元素并删除,队列为空时,抛出异常
E pollFirst() 从对首获取元素并删除,队列为空时,返回null
E pollLast() 从对尾获取元素并删除,队列为空时,返回null
E getFirst() 从对首获取元素但不删除,队列为空时,抛出异常
E getLast() 从对尾获取元素但不删除,队列为空时,抛出异常
E peekFirst() 从对首获取元素但不删除,队列为空时,返回null
E peekLast() 从对尾获取元素但不删除,队列为空时,返回null
boolean removeFirstOccurrence(Object o) 删除队列中第一个与o相等的元素,队列不包含此元素时,则维持不变
boolean removeLastOccurrence(Object o) 从队列中删除最后一个与o相等的元素。当队列中不包含本元素时,则维持不变
boolean add(E e) 添加对象到队尾,当超出队列界限的时候,抛出异常
boolean offer(E e) 添加对象到队尾,当超出队列界限的时候,返回false
E remove() 从对首获取元素并删除,队列为空时,抛出异常
E poll() 从对首获取元素并删除,队列为空时,返回null
E element() 从对首获取元素但不删除,队列为空时,抛出异常
E peek() 从对首获取元素但不删除,队列为空时,返回null

3、Deque用法

  • ArrayDeque: 基于数组实现的线性双向队列
Deque<Integer> stack = new ArrayDeque<Integer>();
  • LinkedList: 基于链表实现的链式双向队列
Deque<Integer> stack = new LinkedList<>();
  • 二者的区别
    ArrayDeque:双端队列,线程不安全,性能高于LinkedList,不允许插入null元素
    LinkedList:双端队列,线程不安全,首尾元素操作效率高,低效随机访问

本文地址:https://blog.csdn.net/miyouyou/article/details/113683903