I have missed a problem with the Java Generic type
public class MyTest {
@Test
public void test1() throws Exception {
List<Integer> list = getMapInstance();
}
public static <T extends Map<Object, Object>> T getMapInstance() {
T t = (T) new HashMap<>();
return t;
}
}
In the code, I assign a T (which extends Map<Object, Object>) to a List, I think it will be intercepted by compile-time type checking. but it successfully complied and when I run it, it throws a ClassCastException
//the bytecode of test1
0 invokestatic #10 <org/example/BugTest.getMapInstance : ()Ljava/util/Map;>
3 checkcast #11 <java/util/List>
6 astore_1
7 return
My JDK version is 11 and 17
I want to know why this code compiles successfully, please
New contributor
user24986407 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.