栈--数组实现

import java.util.Arrays;
import java.util.EmptyStackException;

public class ArrayStack<E> {

    protected Object[] elementData; //数组
    protected int elementCount; //元素个数
    protected int capacityIncrement; //扩容个数

    private static final long serialVersionUID = 1224463164541339165L;

    public ArrayStack(){}

    /**
     * 添加元素
     * @param item
     * @return
     */
    public E push(E item) {

        int minCapacity = elementCount+1;
        if (minCapacity - elementData.length > 0){
            //扩容

            int oldCapacity = elementData.length;
            int newCapacity = oldCapacity + ((capacityIncrement > 0) ?
                    capacityIncrement : oldCapacity);

            if (newCapacity - minCapacity < 0)
                newCapacity = minCapacity;
            elementData = Arrays.copyOf(elementData, newCapacity);
        }
        elementData[elementCount++] = item;

        return item;
    }

    /**
     * 删除元素
     * @return
     */
    public synchronized E pop() {
        E       obj;
        int     len = size();

        //拿到要删除的元素
        obj = peek();

        //做删除操作
        elementData[elementCount] = null;
        elementCount--;

        return obj;
    }

    public synchronized E peek() {
        //判断stack不为空
        int     len = size();
        if (len == 0)
            throw new EmptyStackException();

        int index = len -1;
        //防止数组下标越界
        if (index >= elementCount) {
            throw new ArrayIndexOutOfBoundsException(index + " >= " + elementCount);
        }
        E       obj;
        obj= (E) elementData[index];
        return  obj;
    }


    /**
     * 长度
     * @return
     */
    public synchronized int size() {
        return elementCount;
    }

}

 

posted @ 2018-04-30 09:48  inspire0x001  阅读(117)  评论(0编辑  收藏  举报