为什么 java API 阻止我们一起调用添加和删除?

why java API prevents us to call add and remove together?

根据Java API-

IllegalStateException - if neither next nor previous have been called, or remove or add have been called after the last call to next or previous

remove()- Removes from the list the last element that was returned by next() or previous() (optional operation). This call can only be made once per call to next or previous. It can be made only if add(E) has not been called after the last call to next or previous.

因为每次我们一起调用 addremove 时,它应该删除 add 添加的最后一个元素,为什么这会导致 IllegalStateException

例如在我的代码中-

那为什么java.lang.IllegalStateException同时调用addremove

我的java代码是-

ListIterator<String> listIterator=list.listIterator();
    while(listIterator.hasNext()){
        System.out.println(listIterator.next());
        listIterator.add("Intel");
        listIterator.remove();
        //listIterator.remove();
    } 

调用后 next() 迭代器位于下一个元素。

当我们通过 add() 添加元素时,迭代器在最后添加的元素处向前移动

那为什么在调用 remove()

时有 java.lang.IllegalStateException

来自 Oracle 文档:

Removes from the list the last element that was returned by next() or previous() (optional operation). This call can only be made once per call to next or previous. It can be made only if add(E) has not been called after the last call to next or previous.

好吧,我不知道为什么它被禁止,但正如您所知,javadoc 明确禁止这样做。

然而问题是为什么想要做那样的事情?我唯一想到的是您想替换当前元素(即删除并添加而不是它)。但是,您可以改用 set。见 javadoc:

Replaces the last element returned by next() or previous() with the specified element (optional operation). This call can be made only if neither remove() nor add(E) have been called after the last call to next or previous.

您阅读的文档有误:您应该阅读 ListIterator's javadoc

它说:

Throws:

...

IllegalStateException - if neither next nor previous have been called, or remove or add have been called after the last call to next or previous

现在,如果你想要一个理由,那很简单。你在玩光标。

addremove 之后,您的光标在哪里?你处于不确定的情况。这是一个很难回答的问题,因此最好通过抛出异常来表明不确定性。为了知道它,你必须调用 hasNexthasPrevious 将再次执行所有计算。