繁体   English   中英

Java堆栈接口:IndexOutOfBounds

[英]Java Stacks Interface: IndexOutOfBounds

对于我的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;
    }
}

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

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

我假设只有在堆栈中没有项目时才会出现此错误。 如果堆栈中没有项目,则堆栈中将没有索引,并且调用list.get(0)将毫无意义。

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

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

当然,这是假设“列表”本身不为空。 更好的方法是创建一个单独的方法,以检查一类不变量的列表,这些不变量包括空引用,空堆栈等。但是对于简单赋值而言,这就足够了。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM