Why is the println
printing "tom" and not showing any runtime exception after casting to List<Integer>
, while it is not able to print the value 1 after casting to List<String>
?
import java.util.Arrays;
import java.util.List;
public class Main {
public static void main(String args[]) {
List list = Arrays.asList(1, "tom");
System.out.println(((List<Integer>) list).get(1));
// "tom"
System.out.println(((List<String>) list).get(0));
// ClassCastException: Integer cannot be cast to String
}
}