54 lines
1.1 KiB
Plaintext
54 lines
1.1 KiB
Plaintext
== Why is this an issue?
|
|
|
|
By contract, any implementation of the `java.util.Iterator.next()` method should throw a `NoSuchElementException` exception when the iteration has no more elements.
|
|
Any other behavior when the iteration is done could lead to unexpected behavior for users of this `Iterator`.
|
|
|
|
|
|
=== Noncompliant code example
|
|
|
|
[source,java,diff-id=1,type=noncompliant]
|
|
----
|
|
public class MyIterator implements Iterator<String> {
|
|
...
|
|
public String next() {
|
|
if (!hasNext()) {
|
|
return null;
|
|
}
|
|
// ...
|
|
}
|
|
}
|
|
----
|
|
|
|
|
|
=== Compliant solution
|
|
|
|
[source,java,diff-id=1,type=compliant]
|
|
----
|
|
public class MyIterator implements Iterator<String> {
|
|
...
|
|
public String next() {
|
|
if (!hasNext()) {
|
|
throw new NoSuchElementException();
|
|
}
|
|
// ...
|
|
}
|
|
}
|
|
----
|
|
|
|
== Resources
|
|
|
|
* https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html#next--[JavaDoc 8 - java.util.Iterator]
|
|
|
|
ifdef::env-github,rspecator-view[]
|
|
|
|
'''
|
|
== Implementation Specification
|
|
(visible only on this page)
|
|
|
|
=== Message
|
|
|
|
Add a "NoSuchElementException" for iteration beyond the end of the collection.
|
|
|
|
|
|
endif::env-github,rspecator-view[]
|