内部迭代器类remove方法出现问题



Hi我正在制作一个链表数据结构,并在列表中定义一个迭代器内部类。我当前在删除方法方面遇到问题。我想要的功能是,如果尚未调用下一个或列表中的当前元素已被删除,则无法在上调用它。这是我的东西。

private class ListItr implements java.util.Iterator<E>{
private Node<E> currentNode;
private Node<E> nextNode;
private Node<E> previousNode;

public ListItr(List<E> theList){
  previousNode = new Node<E>(null);
  currentNode = new Node<E>(null);
  nextNode = theList.head;
  currentNode.setSuccessor(nextNode);
}
public boolean hasNext(){        
  return nextNode != null;
}
public E next(){
  if(nextNode == null)
    throw new NoSuchElementException();
  previousNode = currentNode;
  currentNode = nextNode;
  nextNode = nextNode.getSuccessor();
  return currentNode.getElement();
}
public void remove(){
  if(currentNode == null)
    throw new IllegalStateException();
  nextNode = currentNode.getSuccessor();
  previousNode.setSuccessor(nextNode);
  currentNode = null;
  size--;
}

}

正如您所看到的,这将通过拼接列表中的节点,将当前节点设置为null,成功地删除该节点。然而,如果它在第一次调用时没有调用next,它仍然会在我不希望的时候运行。我可以通过添加一个标志nextNotCalled来绕过它,在构造函数中将其设置为true,然后在调用next时将其设置为false。然而,我觉得这不是解决问题的方法…

如果问题是如何做到这一点,我会看看Josh Bloch和Neil Gafter是如何做到的。看看Itr的类定义(第330行)。

最新更新