2023-05-03 11:06:20 +02:00
== Why is this an issue?
2021-06-08 14:23:48 +02:00
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.
2023-05-03 11:06:20 +02:00
=== Noncompliant code example
2021-06-08 14:23:48 +02:00
2022-02-04 17:28:24 +01:00
[source,java]
2021-06-08 14:23:48 +02:00
----
public class MyItr implements Iterator<MyClass> {
//...
public boolean hasNext() {
if (next() != null) { // Noncompliant
return true;
}
return false;
}
----
2023-05-03 11:06:20 +02:00
=== Compliant solution
2021-06-08 14:23:48 +02:00
2022-02-04 17:28:24 +01:00
[source,java]
2021-06-08 14:23:48 +02:00
----
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[]
2021-06-08 15:52:13 +02:00
'''
2021-06-08 14:23:48 +02:00
== Comments And Links
(visible only on this page)
include::comments-and-links.adoc[]
endif::env-github,rspecator-view[]