In Java when casting from an Object to other types, why does the second line produce a warning related to the cast, but the first one doesn\'t?
void a(Object o)
It's because the object won't really be checked for being a List
at execution time due to type erasure. It'll really just be casting it to List
. For example:
List strings = new ArrayList();
strings.add("x");
Object o = strings;
// Warning, but will succeeed at execution time
List integers = (List) o;
Integer i = integers.get(0); // Bang!
See Angelika Langer's Java Generics FAQ for more info, particularly the type erasure section.