The java.util.Iterator.next()
method must throw a NoSuchElementException
when there are no more elements in the
iteration. Any other behavior is non-compliant with the API contract and may cause unexpected behavior for users.
Noncompliant code example
public class MyIterator implements Iterator<String> {
public String next() {
if (!hasNext()) {
return null;
}
// ...
}
}
Compliant solution
public class MyIterator implements Iterator<String> {
public String next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
// ...
}
}