Thursday, January 10th, 2019 code java techniques utils • 170w
We all have been in a position with an Iterator in our hands and trying to pass it to a for each loop. And then for some reason that is totally crazy for a second an error pops up:

"Can only iterate over an array or an instance of java.lang.Iterable"

What... a ok... and then what? You could just fix your logic in order or just google for "java iterator to iterable". But could you just make the iterator also an iterable somehow.

Step one, obviously, add the Iterable interface to your iterator:

public class SuperIterator<T> implements Iterator<T>, Iterable<T> {

Step two, add the missing method by return itself as its iterator:

public Iterator<Character> iterator() {
    return this;