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

356 views Asked by At

As per 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.

Since each time when we calling add and remove together it should remove last element added by add why this cause IllegalStateException

for example in my code-

  • calling each time next() before remove()
  • also remove() is not being called twice without calling next()

then why there is java.lang.IllegalStateException on calling add and remove together.

My java code is-

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

after calling next() iterator is at next element.

when we are adding element by add() iterator moves forward at last element added

then why there is java.lang.IllegalStateException on calling remove()

3

There are 3 answers

2
Olivier Grégoire On BEST ANSWER

You're reading the wrong documentation: you should read ListIterator's javadoc.

It says:

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

Now, if you want a reason, it's rather simple. You're playing with cursors.

After an add or after a remove, where is your cursor? You're in a case of incertitude. That's a difficult question to answer, so it's better to show the incertitude by throwing the exception. In order to know it, you have to call hasNext or hasPrevious which will perform all the calculations again.

0
Anil Reddy Yarragonda On

From Oracle documentation:

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.

2
sodik On

well, I don't know why it is forbidden, but as you already know, javadoc explicitly forbids that.

however question is why do you want to do something like that? Only thing that comes to my mind is that you want to replace current element (i.e. remove and add instead of it). However you can use set instead. See 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.