Java: Casting Object to a generic type

后端 未结 3 503
清酒与你
清酒与你 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:13

    Jon's answer is the right one, but occasionally you can't get around that warning (like when you're working with a legacy API). In those cases you can suppress the warning like so:

    @SuppressWarnings("unchecked")
    List list = (List) someApiThatReturnsNonGenericList();
    

提交回复
热议问题