天天看点

Java集合类框架源码分析 之 Stack源码解析 【9】

Stack在继承Vector基础上,新增了5个方法,使得Vector实现栈先进后出(FILO)的特性,这5方法分别为:

// 在栈顶添加一个元素
    public E push(E item) {} 
	
	// 删除栈顶元素,并返回该元素值
    public synchronized E pop() {}
    
	// 返回栈顶元素值
	public synchronized E peek() {}
	
	// 测试栈是否为空
    public boolean empty() {}
	
	// 搜索一个元素距离栈顶的距离,默认栈顶元素,距离栈顶的距离为1
    public synchronized int search(Object o) {}
           

Stack 源码非常简单,把整个类源码拿过来进行分析:

/*
 * Copyright (c) 1994, 2010, Oracle and/or its affiliates. All rights reserved.
 * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 */

package java.util;

/**
 * Stack 类代表了一个后进先出(LIFO)的对象栈,继承了 Vector ,并使用5种操作,来允许一个 vector 可以被当作 stack 来对待。
 * 提供了常用的push/pop操作,同时peek操作来弹出栈顶的元素,empty来测试栈是否为空,以及 search,来搜索栈中的一个元素,距离栈顶的距离
 * 栈被创建的时候,是空的。
 * 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.
 *
 * Deque接口和它的实现,提供了一系列更彻底,更一致的先进先出操作,在使用选择上,应该优先于当前类。例如:
 *   Deque<Integer> stack = new ArrayDeque<Integer>();}</pre>
 *
 * <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() {
    }

    /**
     * 向栈顶插入一个元素,功能上和 addElement(item)完全一致。
     * 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;
    }

    /**
     * 返回元素距离栈顶的长度,距离如何定义呢?最上边的元素,距离栈顶的距离为1
     * 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;
    }

	// 样例代码:
		Stack<String> stack = new Stack<String>() ;
		for (int i = 0 ;i<10 ;i++){
			stack.add(String.valueOf(i));
		}
		System.out.println(stack); // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
		
		System.out.println(stack.pop() ); // 9
		
		System.out.println(stack); // [0, 1, 2, 3, 4, 5, 6, 7, 8]
		System.out.println(stack.search(String.valueOf(3))); // 6
		System.out.println(stack.search(String.valueOf(8))); //1 最上边的元素,距离栈顶的距离为1
		
}
           

源码都是比较简单明了,search()中有两个点需要注意:

1、如果栈中存在多个和目标元素相同的元素,那么会从栈顶开始,向前搜索第一个元素,返回stack.size()-该位置索引。

2、什么是栈顶?栈顶就是最后插入元素的值,但是对于stack所代表的列表而言,栈顶又是list的末尾,因为索引值最大。

Java集合类框架源码分析 之 Stack源码解析 【9】

3、元素距离栈顶距离的计算方式,以栈顶第一个元素为例,它距离栈顶的距离为1,如何计算出来的呢?

上边的源码中就比较清晰了,就是首先计算该元素的索引:比如元素8,在栈中的索引位置为8,它距离栈顶的距离是:size()-8 = 1;

至此,List接口下,常用的类源码已经分析完毕,若后期发现有其他类,再进行追加解析。

其他相关文章:

Java集合类框架源码分析 之 Stack源码解析 【9】

Java集合类框架源码分析 之 Vector源码解析 【8】

Java集合类框架源码分析 之 AttributeList源码解析 【7】

Java集合类框架源码分析 之 RoleList源码解析 【6】

Java集合类框架源码分析 之 CopyOnWriteArrayList源码解析 【5】

Java集合类框架源码分析 之 LinkedList源码解析 【4】

Java集合类框架源码分析 之 ArrayList源码解析 【3】

Java集合类框架源码分析 之 接口中是否可以有方法实现 【2】

Java集合类框架源码分析 之 List 接口源码分析 【1】