I have code in which an instance of the class that implements the Iterable interface is placed in a foreach , and this not only does not cause objections in the compiler, but it also works. But how - I do not understand.

Code

 class ArrayIterator implements Iterator { private int index = 0; private final int[] values; ArrayIterator(int[] values) { this.values = values; } public boolean hasNext() { return index < values.length; } public Object next() { return values[index++]; } @Override public void remove() { } } class ForEachArray implements Iterable { private final int[] values; ForEachArray(final int[] values) { this.values = values; } public Iterator iterator() { return new ArrayIterator(this.values); } } class Main { public static void main(String[] args) { ForEachArray forEach = new ForEachArray(new int[]{1, 2, 3, 4, 5}); for (Object value : forEach) { System.out.println(value); } } } 

Displays:

 1 2 3 4 5 

Why does an instance of a class that is neither an array nor a collection, hitting a loop in place of a set, works like a set? What happens in the execution thread? How is it that the for loop manages to call the ForEachArray method iterator() ForEachArray (well, that's okay: that's what it is Iterable ), and then hasNext() and next() for ArrayIterator ? That is what is not clear.

  • Here you yourself and explained everything. It remains only to believe that it is so. - Pavel Mayorov
  • Read how the for loop in Java works in any modern tutorial. - Pavel Mayorov
  • 2
    @Pavel this all happens inside the foreach implementation. This is how it works. Getting an iterator and using it (its methods) in a loop. - Regent
  • four
  • 2
    Of course. If only because you would not be able to return it in the public Iterator iterator() method. And if you had implemented it incorrectly (the methods hasNext and next ), then it would have been ForEachArray to run through the elements of ForEachArray normally. - Regent

1 answer 1

For-Each loop

 for (Object value : forEach) { System.out.println(value); } 

works like this :

 for (Iterator i = forEach.iterator(); i.hasNext();) { Object value = i.next(); System.out.println(value); } 

The iterator method of the ForEachArray class is returned by an ArrayIterator . Accordingly, the hasNext and next methods are called just in ArrayIterator .