Stack源码分析

来源:互联网 发布:新闻源软件 编辑:程序博客网 时间:2024/05/29 03:56

Stack

源码基于1.8.0_112

Stack继承自Vector,加入了关键的push、peek、pop方法,具体步骤可参考Vector和ArrayList

原理 :ArrayList内部使用一个数组存储放入的数据,数组使用默认大小初始化,当数组无法再放入更多的对象时,数组会扩大到原来的2倍。

成员变量

全部继承于Vector

构造方法

先阅读默认构造函数,其他构造函数可在阅读完具体操作后再回来阅读

    /**     * 默认构造函数     */    public MyStack() {    }

push(E item)

执行逻辑与Vector的add方法一样,返回值不同

代码

    /**     * 栈顶加入一个元素     * @param item     * @return     */    public E push(E item) {        addElement(item);        return item;    }    // Vector的方法,该方法里调用的逻辑与add一样,只是返回值不同    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)            grow(minCapacity);    }    private void grow(int minCapacity) {        // overflow-conscious code        int oldCapacity = elementData.length;        // 扩容        // 默认 capacityIncrement=0 ,所以每次扩容为原来的2倍        // 指定capacityIncrement,则每次增加 capacityIncrement 的大小        int newCapacity = oldCapacity + ((capacityIncrement > 0) ?                capacityIncrement : oldCapacity);        if (newCapacity - minCapacity < 0)            newCapacity = minCapacity;        if (newCapacity - MAX_ARRAY_SIZE > 0)            newCapacity = hugeCapacity(minCapacity);        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 :                MAX_ARRAY_SIZE;    }

peek()

取出栈顶对象,调用了Vector中的方法

代码

    /**     * 取出栈顶对象     * @return     */    public synchronized E peek() {        int     len = size();        if (len == 0)            throw new EmptyStackException();        return elementAt(len - 1);    }    // Stack peek方法调用    public synchronized int size() {        return elementCount;    }    // Stack peek方法调用    public synchronized E elementAt(int index) {        if (index >= elementCount) {            throw new ArrayIndexOutOfBoundsException(index + " >= " + elementCount);        }        return elementData(index);    }

pop()

调用peek方法取出栈顶对象,并调用Vector的方法删除栈顶对象

代码

    /**     * 取出栈顶对象,并删除栈顶对象     * @return     */    public synchronized E pop() {        E       obj;        int     len = size();        obj = peek();        removeElementAt(len - 1);        return obj;    }

总结

  1. 参考Vector和ArrayList
0 0
原创粉丝点击