I stumbled across a Java casting situation involving Generics and Interfaces that I do not understand.
Please consider the following code where I create a List<Interface1>. And then get() an element and cast it to Interface2 without compiler error although these two interfaces are completely unrelated.
import java.util.*;
public class Main {
public static void main(String ... args) {
List<Interface1> list = new ArrayList<>();
list.add(new Interface1() {});
Interface1 ok = list.get(0);
Interface2 why = (Interface2)list.get(0);
}
}
interface Interface1 {
}
interface Interface2 {
}
Can anyone explain why there is not compiler error for the cast at the second get(0)?
Two side notes: Executing the class throws a ClassCastException (as expected). And using two classes instead of interfaces does actually generate compile errors.