40 lines
889 B
Plaintext
40 lines
889 B
Plaintext
![]() |
The ``++hasNext++`` method of an ``++Iterator++`` should only report on the state of the iterator, not change it. Making a change to an iterator in its ``++hasNext++`` method violates all expectations of what the method will do, and almost guarantees bad results when the iterator class is used.
|
||
|
|
||
|
|
||
|
== Noncompliant Code Example
|
||
|
|
||
|
----
|
||
|
public class MyItr implements Iterator<MyClass> {
|
||
|
//...
|
||
|
|
||
|
public boolean hasNext() {
|
||
|
if (next() != null) { // Noncompliant
|
||
|
return true;
|
||
|
}
|
||
|
return false;
|
||
|
}
|
||
|
----
|
||
|
|
||
|
|
||
|
== Compliant Solution
|
||
|
|
||
|
----
|
||
|
public class MyItr implements Iterator<MyClass> {
|
||
|
private List<MyClass> list;
|
||
|
private int index = 0;
|
||
|
|
||
|
//...
|
||
|
|
||
|
public boolean hasNext() {
|
||
|
return index < list.size();
|
||
|
}
|
||
|
----
|
||
|
|
||
|
|
||
|
ifdef::env-github,rspecator-view[]
|
||
|
== Comments And Links
|
||
|
(visible only on this page)
|
||
|
|
||
|
include::comments-and-links.adoc[]
|
||
|
endif::env-github,rspecator-view[]
|