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) {
Integer i = (Integer) o;
List list = (List) o;
}
/*Type safety: Unchecked cast from Object to List*/
解决方案
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!