Custom Iterable With Iterator
Make a class usable in for-each loops by implementing Iterable and returning an Iterator that honors the hasNext/next contract.
Code
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
public class Playlist implements Iterable<String> {
private final List<String> tracks;
public Playlist(List<String> tracks) {
this.tracks = List.copyOf(tracks);
}
@Override
public Iterator<String> iterator() {
// 每次调用给一个全新游标,多个迭代器互不干扰
return new Iterator<>() {
private int cursor;
@Override
public boolean hasNext() {
return cursor < tracks.size();
}
@Override
public String next() {
if (!hasNext()) {
// 契约要求:没有元素时 next 必须抛 NoSuchElementException
throw new NoSuchElementException();
}
return tracks.get(cursor++);
}
};
}
public static void main(String[] args) {
Playlist playlist = new Playlist(List.of("intro", "theme", "credits"));
// 实现 Iterable 后增强 for 直接可用
for (String track : playlist) {
System.out.println("playing: " + track);
}
// 手动迭代:耗尽后再取 next 按契约抛异常
Iterator<String> it = playlist.iterator();
while (it.hasNext()) {
it.next();
}
try {
it.next();
} catch (NoSuchElementException e) {
System.out.println("exhausted throws: " + e.getClass().getSimpleName());
}
}
}What the code does
Everything happens inside the class Playlist and the functions Playlist, iterator, hasNext and next.
Iteration happens inside for (String track : playlist) — everything outside it runs once. When the guard condition holds, NoSuchElementException is thrown rather than a bogus value returned.
Applying it
The main signature reads public Playlist(List<String> tracks)
Running the file prints labeled results such as playing:, exhausted throws: — each operation’s effect is visible in the output.
Running the file executes main, which drives Playlist, iterator, hasNext and next in order.
Statements that matter
throw new NoSuchElementException();
return cursor < tracks.size();
return tracks.get(cursor++);
FAQ
- How are precondition violations signaled?
- Validation comes first — `NoSuchElementException` marks the failure, before any partial work happens.
- What does Custom Iterable With Iterator print when run?
- No setup needed: run the file and look for labeled lines like `playing:`, `exhausted throws:` in the output.
Report a problem with this exampleOpens a pre-filled issue on GitHub.