liveBook · Manning

Iterable

As explained in 100 Java Mistakes and How to Avoid Them

Iterable is a Java interface whose objects can provide an Iterator for traversing their elements.

An Iterable supplies an Iterator for traversal. The common enhanced-for path is only one valid usage: it checks hasNext(), calls next(), runs the body, and repeats. section 8.13

The central mistake is implementing an iterator that works only when hasNext() precedes every next(). Collection utilities may call next() first, repeat operations, or expose exhaustion directly. section 8.13

Correct range iterator

A range iterator keeps state in next(), checks exhaustion, and throws NoSuchElementException when no element remains. IntStream.range(0, max).iterator() avoids custom implementation when suitable.

Apply these safeguards when exposing an Iterable:

  • Make next() work without a preceding hasNext() and throw NoSuchElementException after exhaustion. section 8.13

How 100 Java Mistakes and How to Avoid Them covers it

How deep it goes
Explains enhanced-for mechanics and iterator contracts, then demonstrates stateful and buffered implementations.
Examples
Demonstrates numeric ranges, Collections.min(), BufferedReader lines, and IntStream.range().iterator().
What it assumes
Assumes Java collection and enhanced-for familiarity while illustrating iterator behavior through focused implementations.
What you can do after
Builds contract-compliant custom iterators and diagnose implementations that depend on enhanced-for-only call patterns.
How it connects
Connects Iterable with Iterator, enhanced-for statements, Collection, Map, Collections.min(), Collections.max(), and NoSuchElementException.

Also explained in

Compare how 7 books explain iterable →

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.