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?