泛型类中无法实例化泛型数组和unchecked cast的解决办法

资料:

Type safety: Unchecked cast

 

 

As the messages above indicate, the List cannot be differentiated between a List<Object> and a List<String> or List<Integer>.

I've solved this error message for a similar problem:

List<String> strList = (List<String>) someFunction();
String s = strList.get(0);

with the following:

List<?> strList = (List<?>) someFunction();
String s = (String) strList.get(0);

Explanation: The first type conversion verifies that the object is a List without caring about the types held within (since we cannot verify the internal types at the List level). The second conversion is now required because the compiler only knows the List contains some sort of objects. This verifies the type of each object in the List as it is accessed.

 

JDK中也是类中存Object数组,取元素的时候强转元素的类型,而不是将数组强转

PriorityQueue

 

 

 

posted @ 2020-10-22 16:40  Numerz  阅读(506)  评论(0编辑  收藏  举报