未经检查的转换为实现 Map<String, V> 的泛型类
我试图理解为什么这个代码有一个未经检查的强制转换警告。前两个演员没有警告,但第三个演员有:
class StringMap<V> extends HashMap<String, V> {
}
class StringToIntegerMap extends HashMap<String, Integer> {
}
Map<?, ?> map1 = new StringToIntegerMap();
if (map1 instanceof StringToIntegerMap) {
StringToIntegerMap stringMap1 = (StringToIntegerMap)map1; //no unchecked cast warning
}
Map<String, Integer> map2 = new StringMap<>();
if (map2 instanceof StringMap) {
StringMap<Integer> stringMap2 = (StringMap<Integer>)map2; //no unchecked cast warning
}
Map<?, Integer> map3 = new StringMap<>();
if (map3 instanceof StringMap) {
StringMap<Integer> stringMap3 = (StringMap<Integer>)map3; //unchecked cast warning
}
这是对演员的完整警告:stringMap3
类型安全:未经检查的从 到
Map<capture#3-of ?,Integer>
StringMap<Integer>
但是,类声明指定了 第一个类型参数 (即 ),并且两者和强制转换都对第二个类型参数 (即 ) 使用相同的类型。据我所知,只要演员不投掷(并且不应该,因为有检查),将是有效的 。StringMap
Map
String
map3
StringMap<Integer>
Map
Integer
ClassCastException
instanceof
stringMap3
Map<String, Integer>
这是Java编译器的局限性吗?或者,如果忽略警告,则使用某些参数调用 map3 或 stringMap3 的方法可能会导致意外情况?ClassCastException