1

I found this code snippet and have been having trouble fully understanding its implementation. I know it has one method:

Iterator<T> iterator()

which creates a new iterator. But what is the point of this one method. In this example:

import java.util.Iterator;

public class Range implements Iterable<Integer> {
  private int start, end;
  public Range(int start, int end) {
    this.start = start;
    this.end = end;
  }

  public Iterator<Integer> iterator() {
    return new RangeIterator();
  }
}

public static void main(String[] args) {
  Range range = new Range(1, 10);
  for(Integer cur : range) {
    System.out.println(cur);
  }
}

The code works correctly, yet iterator() has never been called. I know you need the Iterable interface to use the for each loop, but what is the point of the one method inside the interface? Any help in clearing this confusion would be appreciated.

dda
  • 6,030
  • 2
  • 25
  • 34
john woolstock
  • 177
  • 1
  • 7
  • 3
    It's called implicitly by the enhanced for-loop. – azurefrog Nov 27 '15 at 19:34
  • 1
    Exactly as @azurefrog states -- it's called behind the scenes, and that's the main reason for implementing the interface -- to allow use of the for-each loop. – Hovercraft Full Of Eels Nov 27 '15 at 19:35
  • [Here's a good blog post](https://blogs.oracle.com/CoreJavaTechTips/entry/using_enhanced_for_loops_with) from oracle discussing these loops, and [here is the documentation](https://docs.oracle.com/javase/8/docs/technotes/guides/language/foreach.html) from the oracle tutorials explaining them. – azurefrog Nov 27 '15 at 19:38
  • Well, know this makes much more sense. Thank you! – john woolstock Nov 27 '15 at 19:39

0 Answers0