java.util.Stack類簡介


Stack是一個后進先出(last in first out,LIFO)的堆棧,在Vector類的基礎上擴展5個方法而來

Deque(雙端隊列)比起Stack具有更好的完整性和一致性,應該被優先使用

  1. E push(E item)      把項壓入堆棧頂部。   
  2. E pop()        移除堆棧頂部的對象,並作為此函數的值返回該對象。   
  3. E peek()          查看堆棧頂部的對象,但不從堆棧中移除它。   
  4. boolean empty()         測試堆棧是否為空。    
  5. int search(Object o)      返回對象在堆棧中的位置,以 1 為基數。 

Stack本身通過擴展Vector而來,而Vector本身是一個可增長的對象數組( a growable array of objects)那么這個數組的哪里作為Stack的棧頂,哪里作為Stack的棧底?

答案只能從源代碼中尋找,jdk1.6:

  1. public class Stack<E> extends Vector<E> {  
  2. /** 
  •     * 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). 
  •      * @exception  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). 
  •      * @exception  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;  
  • }
  • 通過peek()方法注釋The object at the top of this stack (the last item of the Vector object,可以發現數組(Vector)的最后一位即為Stack的棧頂
  • pop、peek以及search方法本身進行了同步

    push方法調用了父類的addElement方法

    empty方法調用了父類的size方法

    Vector類為線程安全類

    綜上,Stack類為線程安全類(多個方法調用而產生的數據不一致問題屬於原子性問題的范疇)

    • public class Test {  
    • public static void main(String[] args) {  
    •         Stack<String> s = new Stack<String>();  
  •        System.out.println("------isEmpty");  
    •         System.out.println(s.isEmpty());  
    •         System.out.println("------push");  
    •         s.push("1");  
    •         s.push("2");  
    •         s.push("3");  
    •         Test.it(s);  
    •         System.out.println("------pop");  
    •         String str = s.pop();  
    •         System.out.println(str);  
    •         Test.it(s);  
    •         System.out.println("------peek"); 
    •     str = s.peek();  
    •         System.out.println(str);  
    •         Test.it(s);  
    •         System.out.println("------search");  
    • int i = s.search("2");  
    •         System.out.println(i);  
    •         i = s.search("1");  
    •         System.out.println(i);  
    •         i = s.search("none");  
    •         System.out.println(i);  
    •     }  
    • public static void it(Stack<String> s){  
    •         System.out.print("iterator:");  
    •         Iterator<String> it = s.iterator();  
    • while(it.hasNext()){  
    •             System.out.print(it.next()+";");  
    •         }  
    •         System.out.print("\n");  
    •     }  
      • 結果:
        • ------isEmpty  
        • true            
        • ------push  
        • iterator:1;2;3;    
        • ------pop  
        • 3       --棧頂是數組最后一個  
        • iterator:1;2;  
        • ------peek  
        • 2       --pop取后刪掉,peek只取不刪  
        • iterator:1;2;  
        • ------search      
        • 1       --以1為基數,即棧頂為1  
        • 2       --和棧頂見的距離為2-1=1  
        • -1      --不存在於棧中 
        • Stack並不要求其中保存數據的唯一性,當Stack中有多個相同的item時,調用search方法,只返回與查找對象equal並且離棧頂最近的item與棧頂間距離(見源碼中search方法說明)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM