My Code
import java.util.*;
public class Test<T> implements Iterable<T> {
private List<T> persons = new ArrayList<T>();
public static void main(String[] args) {
Test<Test> ob = new Test<Test>();
ob.persons.add(ob);
for (Test t : ob.iterator()) {
System.out.println();
}
}
@Override
public Iterator<T> iterator() {
return persons.iterator();
}
}
Error:
Can only iterate over an array or an instance of java.lang.Iterable
What's adifference between two, Why A can't be legal and B is working ?
for (Test t : ob.iterator()) { ----------------------A
System.out.println();
}
while (ob.iterator().hasNext()) { -------------------------- B
System.out.println();
}
Want to know why A underlying code is not working ? Is something different happening in for loop ? While
and for
both are provided the same iterator state to be iterated.