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.
forloop in Java works in any modern tutorial. - Pavel Mayorovpublic Iterator iterator()method. And if you had implemented it incorrectly (the methodshasNextandnext), then it would have beenForEachArrayto run through the elements ofForEachArraynormally. - Regent