hasNext() of an iterator calls its own next()

tx0/java:has-next-calls-nextdefaultwarningbug

What it finds

hasNext() of an iterator that calls its own next() moves the iterator forward each time someone asks whether there is more: every check skips an element.

Reported in classes that implement Iterator or ListIterator themselves, for calls of next() without a receiver or on this.

From the rule's source, has_next_calls_next.rs.

Example from the rule's tests
import java.util.Iterator; class Lines implements Iterator<String> {  private String pending;   @Override  public boolean hasNext() {    return next() != null;tx0 reports: hasNext() calls next()  }   @Override  public String next() {    return pending;  }} class Wrapper implements Iterator<String> {  private final Iterator<String> inner = null;  private String peeked;   @Override  public boolean hasNext() {    if (peeked == null && inner.hasNext()) {      peeked = inner.next();    }    return peeked != null;  }   @Override  public String next() {    String p = peeked;    peeked = null;    return p;  }}
Highlighted lines are the ones tx0 reports, with its message under each; the other lines are left alone.

Turn it on, off or suppress it

The rule runs in every tier. To turn it off for a project, set its level in tx0.toml:

tx0.toml
[rules]
"tx0/java:has-next-calls-next" = "off"

To keep one finding, suppress it with a reason. tx0 suppress ID --reason "..." writes the comment on the line before the code:

// tx0: ignore[tx0/java:has-next-calls-next] reason="..."

tx0 explain tx0/java:has-next-calls-next shows the same in the terminal. Found a false positive? Report it.