Java 如何在迭代器类中为堆栈实现remove方法?
我正在编写一个使用迭代器的ArrayStack类。我知道对堆栈使用迭代器不一定有意义,但这是为了家庭作业。我在删除方法上有问题。我理解它的描述,但我在实现它时遇到了困难。下面是我的程序的内部类:Java 如何在迭代器类中为堆栈实现remove方法?,java,iterator,stack,inner-classes,Java,Iterator,Stack,Inner Classes,我正在编写一个使用迭代器的ArrayStack类。我知道对堆栈使用迭代器不一定有意义,但这是为了家庭作业。我在删除方法上有问题。我理解它的描述,但我在实现它时遇到了困难。下面是我的程序的内部类: private class StackIterator implements Iterator<Item> { private int index; private boolean canremove; public StackIte
private class StackIterator implements Iterator<Item> {
private int index;
private boolean canremove;
public StackIterator() {
index = size - 1;
canremove = false;
}
@Override
public boolean hasNext()
{
return index > 0;
}
@Override
public Item next()
{
if (!hasNext()) {
throw new NoSuchElementException("There is no next element"+
" in the stack.");
}
canremove = true;
return contents[--index];
}
@Override
public void remove() {
if (!canremove) {
throw new IllegalStateException("Can only remove an element"
+ "after a call to the next method has been made.");
}
canremove = false;
}
}
私有类StackIterator实现迭代器{
私有整数索引;
私有布尔可删除;
公共堆栈迭代器(){
指数=大小-1;
canremove=false;
}
@凌驾
公共布尔hasNext()
{
回归指数>0;
}
@凌驾
公共项目下一步()
{
如果(!hasNext()){
抛出新的NoSuchElementException(“没有下一个元素”+
“在堆栈中。”);
}
canremove=true;
返回内容[--索引];
}
@凌驾
公共空间删除(){
如果(!可以删除){
抛出新的IllegalStateException(“只能删除元素”
+“在调用下一个方法之后。”);
}
canremove=false;
}
}
我实际上如何删除该元素?我只是缩小尺寸吗?还是我需要更多的变量来跟踪?非常感谢您的帮助。您可能需要将数组中的所有内容移回一个空格。或者你不能支持它。我也认为你应该摆脱
canremove
。可能只需检查index>=0和index