In the snippet below, [1] seems to yield the expected result whereas, [2] throws a ClassCastException as shown in the results below.
Why is a ClassCastException thrown when calling iterator() and not when using method reference?
List<String> philosophers = Arrays.asList("Seneca", "Epictetus");
// [1]
for (String s : (Iterable<? extends String>) philosophers::iterator) {
System.out.println(s);
}
// [2]
for (String s: (Iterable<? extends String>) philosophers.iterator()) {
System.out.println(s);
}
[1] (Result when using method reference)
`Seneca`
`Epictetus`
[2] (Result when calling iterator())
Exception in thread "main" java.lang.ClassCastException: class java.util.Arrays$ArrayItr cannot be cast to class java.lang.Iterable`