liveBook · Manning

Next

As explained in 100 Java Mistakes and How to Avoid Them

Iterator.next is the Java Iterator method that returns the next element and throws NoSuchElementException when none remains.

Iterator.next() returns the next element. When no element remains, it must throw NoSuchElementException. Implementations that work only with enhanced for loops can violate this contract. section 8.13

A next() implementation that respects the contract

Track the current position in next(), check exhaustion there, return the current value, and then advance: if (!hasNext()) throw new NoSuchElementException(); return cur++; This supports calls to next() before hasNext() and repeated calls after exhaustion. section 8.13

Avoid these iterator mistakes:

  • Make next() work without a preceding hasNext(), and throw NoSuchElementException when exhausted. section 8.13

How 100 Java Mistakes and How to Avoid Them covers it

How deep it goes
Explains call ordering, exhaustion behavior, buffering, and corrected implementations, but does not discuss iterator removal.
Examples
Uses numeric range iterators, Collections.min(), BufferedReader iteration, and standard stream-based iterator alternatives.
What it assumes
Assumes familiarity with Java collections, iterators, enhanced for statements, and exceptions.
What you can do after
Build custom iterators that remain correct under direct next() calls, unusual call sequences, and exhaustion.
How it connects
Connects Iterator.next() to hasNext(), Iterable, enhanced for statements, NoSuchElementException, and collection utility methods.

Also explained in

Compare how 5 books explain next →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Java Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.