Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterator: One past the last element in Java

Tags:

java

iterator

Like in C++, we have end() where the iterator ends up at the position one past the last element, is it true for Java iterator has well?

while (iterator.hasNext()) {
    String color = iterator.next();
}

E.g. In C++, we have:

Blue Green Purple
  ^    ^     ^    ^
begin            end

How would I have to draw the above illustration in Java thinking/terminology?

like image 953
user963241 Avatar asked Jun 11 '26 05:06

user963241


1 Answers

In Java, Iterator is an interface meaning that there has to be a concrete class implementing the methods of the interface. Now that depends on the type of collection that is used. As an example, to iterate on a collection of the type List, we use a ListIterator.

For a listIterator, there is no current element that it holds. The cursor position would lie between elements, at the beginning of the collection or at the end of the last element in the list. The illustration should make it more clear.

So, when hasNext() returns false, you know you are at the end of the Collection (List, in our case) which throws a NoSuchElementException.

Sample of a listIterator

like image 134
Joey Ezekiel Avatar answered Jun 13 '26 20:06

Joey Ezekiel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!