对于我的CS类,我必须编写一个从LinkedList延伸出来的Stacks接口。但是,我的peek()方法显然存在错误。当我将其实现到其他程序之一时,我返回一个IndexOutOfBounds异常(索引0;大小0),我似乎无法找到在我的peek()方法中为我处理的异常或语句。Java Stacks接口:IndexOutOfBounds
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;
}
}
你的数据结构有点混乱。你扩展了'LinkedList',但是你的结构还包含一个'ArrayList',即使有人调用其他方法可以产生意想不到的结果,堆栈方法也能正常工作。这并不能帮助你的bug只是一个全面的观察。 –
因为0不是空列表的有效索引,所以您无法在空列表上调用get(0)。读取您使用的类和方法的javadoc:https://docs.oracle.com/ javase/8/docs/api/java/util/List.html#get-int- –
您正在尝试获取第0个元素,因为它不存在会导致索引超出范围。难道你没有其他方法来检查是否存在任何元素? –