-1

我从以下代码收到错误“类型堆栈不采用参数公共类 ArrayStack 实现堆栈”:

public class ArrayStack<E> implements Stack<E> {

private E[] data;

private int size;

public ArrayStack() {
data = (E[])(new Object[1]);
size = 0;
}

public boolean isEmpty() {
return size == 0;
}

public Object pop() {
if (isEmpty()) {
    throw new EmptyStructureException();
}
size--;
return data[size];
}

public Object peek() {
if (isEmpty()) {
    throw new EmptyStructureException();
}
return data[size - 1];
}

protected boolean isFull() {
return size == data.length;
}

public void push(Object target) {
if (isFull()) {
    stretch();
}
data[size] = target;
size++;
}

protected void stretch() {
E[] newData = (E[])(new Object[data.length * 2]);
for (int i = 0; i < data.length; i++) {
    newData[i] = data[i];
}
data = newData;
}   
}

“类型堆栈不带参数公共类ArrayStack实现堆栈”

堆栈类如下。

public interface Stack<E> {

public boolean isEmpty();

public E peek();

public E pop();

public void push(E target);

}
4

1 回答 1

0

你的 peek() 方法应该是这样的

    public E peek() throws EmptyStructureException {
        if (isEmpty()) {
          throw new EmptyStructureException();
        }
        return (E)data[size - 1];
    }

你的 push() 方法应该是这样的

   public void push(E target) {
         if (isFull()) {     
            stretch();
         }
         data[size] = target;
         size++;
   }

你的 pop() 方法应该是这样的

    public E pop() throws EmptyStructureException {
         if (isEmpty()) {
             throw new EmptyStructureException();
         }
         size--;
         return (E)data[size];
    }

现在您的界面如下所示

public interface Stack<E> {

      public boolean isEmpty();

      public E peek() throws EmptyStructureException;

      public E pop() throws EmptyStructureException;

      public void push(E target);

}
于 2013-10-10T00:45:58.173 回答