rspec/rules/S2272/java/rule.adoc

52 lines
1.1 KiB
Plaintext

== Why is this an issue?
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
[source,java,diff-id=1,diff-type=noncompliant]
----
public class MyIterator implements Iterator<String> {
public String next() {
if (!hasNext()) {
return null;
}
// ...
}
}
----
=== Compliant solution
[source,java,diff-id=1,diff-type=compliant]
----
public class MyIterator implements Iterator<String> {
public String next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
// ...
}
}
----
== Resources
=== Documentation
* https://docs.oracle.com/javase/7/docs/api/java/util/Iterator.html#next--[Java SE 7 API Specification: 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[]