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
}
}
The first call of println
is statically dispatched to PrintStream.println(Object)
and the second call is dispatched to PrintStream.println(String)
. So for the second call the compiler puts an implicit cast to String
which then fails with ClassCastException
at runtime.
The problem here is that the java compiler picks methods at compile time, not runtime.
And at compile time it will pick the method PrintStream.print(String)
, not PrintStream.print(int)
or PrintStream.print(Object)
, both of which would succeed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With