work hard work smart

专注于Java后端开发。 不断总结,举一反三。
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

Stack源码解析

Posted on 2020-04-04 21:20  work hard work smart  阅读(128)  评论(0编辑  收藏  举报

Stack介绍

Stack(栈),它具有先进后出的特性

 

1、Stack的源码结构

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

 Stack继承了Vector,而Vector又是线程安全的ArrayList,所以底层仍然是数组。

 

2、入栈操作

    public E push(E item) {
	// 直接调用了Vector.addElement
        addElement(item);

        return item;
    }

    //Vector.addElement
    public synchronized void addElement(E obj) {
        modCount++;
 	//扩容,
        ensureCapacityHelper(elementCount + 1);
	//存放值到最后一位
        elementData[elementCount++] = obj;
    } 

入栈操作就是将数据添加到数组最后一位 

 

3、查看站点元素

    public synchronized E peek() {
        int     len = size();

        if (len == 0)
            throw new EmptyStackException();
	//获取数组最后一位数据
        return elementAt(len - 1);
    }

  

 

4、出栈操作

    public synchronized E pop() {
        E       obj;
        int     len = size();
	//获得栈顶元素
        obj = peek();
	//移除最后一位元素,调用Vector.removeElementAt
        removeElementAt(len - 1);

        return obj;
    }

    //Vector.removeElementAt
    public synchronized void removeElementAt(int index) {
        modCount++;
        if (index >= elementCount) {
            throw new ArrayIndexOutOfBoundsException(index + " >= " +
                                                     elementCount);
        }
        else if (index < 0) {
            throw new ArrayIndexOutOfBoundsException(index);
        }
	//移动数组
        int j = elementCount - index - 1;
        if (j > 0) {
            System.arraycopy(elementData, index + 1, elementData, index, j);
        }
        elementCount--;
	//将最后一位置为null
        elementData[elementCount] = null; /* to let gc do its work */
    }

  

5、查询元素

    public synchronized int search(Object o) {
        //调用Vector.lastIndexOf。获得元素在数字中的索引
	int i = lastIndexOf(o);

	//对应栈来说,如果是最后一个元素,它就是栈顶,index也就是1,所有最后要size() - i;
        if (i >= 0) {
            return size() - i;
        }
        return -1;
    }
    //Vector.lastIndexOf
    public synchronized int lastIndexOf(Object o) {
        return lastIndexOf(o, elementCount-1);
    }

    //Vector.lastIndexOf(Object o, int index)
    //遍历数组查询对象
    public synchronized int lastIndexOf(Object o, int index) {
        if (index >= elementCount)
            throw new IndexOutOfBoundsException(index + " >= "+ elementCount);

        if (o == null) {
            for (int i = index; i >= 0; i--)
                if (elementData[i]==null)
                    return i;
        } else {
            for (int i = index; i >= 0; i--)
                if (o.equals(elementData[i]))
                    return i;
        }
        return -1;
    }