基础数据机构之Stack栈源码分析

1.Stack属于经典的数据结构栈,后入先出。方法有pop弹栈,push压栈,isEmpty判断栈空,isFull判断栈满

   java源码中stack继承vector基础数据结构,有多线程安全特性。


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) {			//入栈,向Vector容器尾部追加一个item
        addElement(item);			//Vector容器内部做了扩容逻辑

        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);	//尾部数据移除出vector容器

        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.Vector扩容逻辑

 

 public synchronized void addElement(E obj) {
        modCount++;
        ensureCapacityHelper(elementCount + 1);		//扩容逻辑
        elementData[elementCount++] = obj;		//尾部追加元素
}

private void ensureCapacityHelper(int minCapacity) {
        // overflow-conscious code
        if (minCapacity - elementData.length > 0)			//如果增加后的元素超出element申请的空间的容量
            grow(minCapacity);						//扩容逻辑
}


vector真正的扩容逻辑

 private void grow(int minCapacity) {
        // overflow-conscious code
        int oldCapacity = elementData.length;				//oldCapacity原来容器大小
        int newCapacity = oldCapacity + ((capacityIncrement > 0) ?	//newCapacity新容量大小为oldCapacity+扩容因子capacityIncrement	
                                         capacityIncrement : oldCapacity);
        if (newCapacity - minCapacity < 0)				//新的容量小于minCapacity
            newCapacity = minCapacity;					//新的容量为minCapacity
        if (newCapacity - MAX_ARRAY_SIZE > 0)				//新的容量小于MAX_ARRAY_SIZE
            newCapacity = hugeCapacity(minCapacity);			//新的容量为Integer.MAX_VALUE
        elementData = Arrays.copyOf(elementData, newCapacity);		//生成一段新的容量大小数组
    }



private static int hugeCapacity(int minCapacity) {
        if (minCapacity < 0) // overflow							//如果超出了有符号整型数据溢出,超出了容量限制为负数
            throw new OutOfMemoryError();							//
        return (minCapacity > MAX_ARRAY_SIZE) ?						//获取最大的Integer.Max_Value 0x7fffffff -> 2147483647
            Integer.MAX_VALUE :
            MAX_ARRAY_SIZE;
    }





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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值