Oak
Oak

Reputation: 693

Why is the method .hasNext() returning true?

In the following piece of code:

int i = element.getList().indexOf(element);
boolean test = element.getList().listIterator(i).hasNext();

test is returning true

however if I call element.getList().size() it returns 1

element was the only thing added to the list, so when I ask for the size it does seem to be functioning properly. However hasNext() keeps returning true even though there's only one thing in the whole list.

What am I missing here?

Upvotes: 0

Views: 757

Answers (1)

Jack
Jack

Reputation: 133557

You are missing the fact that without calling next() on the Iterator, you are not consuming the only one item present.

As documentation states about listIterator(int index) (and it holds for the generic iterator too):

Returns a list iterator over the elements in this list (in proper sequence), starting at the specified position in the list. The specified index indicates the first element that would be returned by an initial call to next. An initial call to previous would return the element with the specified index minus one.

The iterator is in a state similar to the following:

iterator position
v
|   element   |

So as you can see you hasNext() is right to return true.

Upvotes: 2

Related Questions