Java: Casting Object to a generic type

后端 未结 3 502
清酒与你
清酒与你 2021-02-05 09:27

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)          


        
3条回答
  •  情歌与酒
    2021-02-05 10:08

    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.

提交回复
热议问题