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()
beforeremove()
- also
remove()
is not being called twice without callingnext()
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()
You're reading the wrong documentation: you should read
ListIterator
's javadoc.It says:
Now, if you want a reason, it's rather simple. You're playing with cursors.
After an
add
or after aremove
, 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 callhasNext
orhasPrevious
which will perform all the calculations again.