如何在Java中创建通用堆栈弹出方法

时间:2019-03-11 02:07:05

标签: java arrays generics stack

我目前正在一个Stack项目上,我正在其中创建一个通用Stack类。我一直在为此寻找堆栈溢出,但找不到它。我需要在代码中创建pop方法的帮助。

这是我到目前为止所拥有的:

public class Stack<E>
{
public static final int DEFAULT_CAPACITY = 10;
private E [] elementData;
private int size;

@SuppressWarnings("unchecked")
public Stack()
{
    this.elementData = (E[]) new Object[DEFAULT_CAPACITY];
}
@SuppressWarnings("unchecked")
public Stack(int capacity)
{
    if(capacity < 0)
    {
        throw new IllegalArgumentException("capacity " + capacity);
    }
    this.elementData = (E[]) new Object[capacity];
}
public boolean isEmpty()
{
    if(size == 0)
    {
        return true;
    }
    else
    {
        return false;
    }
}
/*
The push method should add its parameter to the top of the stack.
*/
public void push(E item)
{
    ensureCapacity(size+1);
    elementData[size] = item;
    size++;
}
private void ensureCapacity(int capacity)
    {
    if(elementData.length < capacity)
    {
        int newCapacity = elementData.length * 2 + 1;
        elementData = Arrays.copyOf(elementData, newCapacity);
    }
}

我在这里需要帮助。我需要删除pop方法并在堆栈顶部返回该元素。如果没有项目 存在,它应该引发“ EmptyStackException”。

    public E pop()
    {
    if(isEmpty())
    {
        throw EmptyStackException
    }
    else
    {

    }
}
}

2 个答案:

答案 0 :(得分:0)

我想通了,我把功劳归功于@ScaryWombat。代码是:

public E pop()
{
    if(isEmpty())
    {
        throw new EmptyStackException();
    }
    else
        {
            return elementData[--size];
    }

}

答案 1 :(得分:-1)

public E pop()
 {
    E item;

    if(isEmpty())
    {
        throw new EmptyStackException();
    }
    else
    {
        item = elementData[size];
        size--;
    }
    return item;
}

您需要使返回变量等于堆栈数组的顶部,然后递减堆栈数组。另外,您需要通过设置size = 0来初始化堆栈。

相关问题