Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generics List<String> and List<Integer> not behaving as expected

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
    }
}
like image 614
Aman Avatar asked Oct 08 '14 06:10

Aman


2 Answers

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.

like image 160
ZhekaKozlov Avatar answered Nov 03 '22 01:11

ZhekaKozlov


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.

like image 30
Sean Patrick Floyd Avatar answered Nov 03 '22 01:11

Sean Patrick Floyd