== Why is this an issue?

An `Iterable` should not implement the `Iterator` interface or return `this` as an `Iterator`.
The reason is that `Iterator` represents the iteration process itself, while `Iterable` represents the object we want to iterate over.

The `Iterator` instance encapsulates state information of the iteration process, such as the current and next element.
Consequently, distinct iterations require distinct `Iterator` instances, for which `Iterable` provides the factory method `Iterable.iterator()`.

This rule raises an issue when the `Iterable.iterator()` of a class implementing both `Iterable` and `Iterator` returns `this`.

=== What is the potential impact?

The `Iterable.iterator()` method returning the same `Iterator` instance many times would have the following effects:

1. For subsequent iterations, e.g., two subsequent `for` loops with iterators over the same object, only the first one would iterate, and the others would do nothing.
2. For nested iterations over the same object, the different iteration processes would affect each other because they only have a common, shared state.

== How to fix it

=== Code examples

==== Noncompliant code example

[source,java,diff-id=1,diff-type=noncompliant]
----
class FooIterator implements Iterator<Foo>, Iterable<Foo> {
  private Foo[] seq;
  private int idx = 0;

  public boolean hasNext() {
    return idx < seq.length;
  }

  public Foo next() {
    return seq[idx++];
  }

  public Iterator<Foo> iterator() {
    return this; // Noncompliant
  }
  // ...
}
----

==== Compliant solution

[source,java,diff-id=1,diff-type=compliant]
----
class FooSequence implements Iterable<Foo> {
  private Foo[] seq;

  public Iterator<Foo> iterator() {
    return new Iterator<Foo>() { // Compliant
      private int idx = 0;

      public boolean hasNext() {
        return idx < seq.length;
      }

      public Foo next() {
        return seq[idx++];
      }
    };
  }
  // ...
}
----

== Resources

=== Documentation

* https://docs.oracle.com/javase/7/docs/api/java/lang/Iterable.html[Java SE 7 API Specification: java.lang.Iterable]
* https://docs.oracle.com/javase/7/docs/api/java/util/Iterator.html[Java SE 7 API Specification: java.util.Iterator]
* https://docs.oracle.com/javase/specs/jls/se7/html/jls-14.html#jls-14.14.2[Java 7 Language Specification: The enhanced for statement] (since Java 1.5)

ifdef::env-github,rspecator-view[]

'''
== Implementation Specification
(visible only on this page)

=== Message

Refactor this code so that the Iterator supports multiple traversal


=== Highlighting

iterator implementation


endif::env-github,rspecator-view[]
