mrbela
mrbela

Reputation: 4647

Iterator of iterable object should return the iterable object itself in Java

Suppose you have given a class in Java that extends the Iterable interface. This class has to provide an Iterator that should return the instance of the surrounding class, take a look at the main method.

public class Test implements Iterable<Test> {

    @Override
    public Iterator<Test> iterator() {

        return new Iterator<Test>() {
          private boolean onlyOnce = false;

            @Override
            public boolean hasNext() {
                return false;
            }

            @Override
            public Test next() {         
               if (!onlyOnce) {
                 onlyOnce = true;
                 // TODO return
               } 
               throw new NoSuchElementException("Iterator has already been called");
            }
        };
    }
    public static void main(String[] args) {

        Test test = new Test();
        Test test2 = test.iterator().next();

        boolean b = test == test2; // should be true
    }

}

How could this issue be solved in Java?

Upvotes: 0

Views: 496

Answers (1)

Andy Turner
Andy Turner

Reputation: 140544

In order to return the enclosing instance of Test, use a qualified this:

return Test.this;

However, a much neater way to implement the method would be to use an existing iterator implementation:

@Override
public Iterator<Test> iterator() {
  return Arrays.asList(this).iterator();
  // or Collections.singleton(this).iterator()
  // or Stream.of(this).iterator()
  // or many other possibilities.
}

Upvotes: 3

Related Questions