Java Stacks接口:IndexOutOfBounds

时间:2017-10-13 19:55:43

标签: java

对于我的CS类,我必须编写一个从LinkedList扩展的Stacks接口。但是,我的peek()方法显然有错误。当我将其实现到我的其他程序中时,我返回一个IndexOutOfBounds异常(索引0;大小为0),我似乎无法找到在我的peek()方法中为我处理的异常或语句。

    public class MyStack<anyType> extends LinkedList<anyType> {
    private ArrayList<anyType> list;

    public MyStack() {
        list = new ArrayList<anyType>(10);
    }

    public void push(anyType x) {
        list.add(0, x);
    }
    public anyType pop() {
        if (list.get(0) == null) {
            return null;
        } else {
            anyType x = list.get(0);
            list.remove(0);
            return x;
        }
    }
    public anyType peek() {
      if (list.get(0) == null) {
         return null;
      } else {
         anyType x = list.get(0);
           return x;
      }
    }
    public boolean isEmpty() {
        if (list.size() == 0)
            return true;
        else
            return false;
    }
}

2 个答案:

答案 0 :(得分:3)

在检查list.get(0)== null之前,您需要检查列表是否存在于该索引中。使用:`

if(list.size() <= 0 || list.get(0) == null) 
return null

答案 1 :(得分:0)

我假设您在堆叠中没有任何项目时才会收到此错误。如果您的堆栈中没有项目,那么您的堆栈将没有索引并且调用list.get(0)没有意义。

您需要处理没有索引的空堆栈的情况:

if (list.size() == 0) return null;

当然,这是假设&#34; list&#34;本身并不是空的。更好的方法是创建一个单独的方法来检查包含空引用,空堆栈等内容的类不变量列表。但是出于简单赋值的目的,这就足够了。

相关问题