我试图理解为什么这段代码有一个未经检查的强制转换警告。前两个演员没有警告,但第三个:
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(ie, ) 的第一个类型参数,并且String两者都使用相同的类型作为(ie, )的第二个类型参数。据我了解,只要演员不抛出(并且不应该因为有检查),就会是有效的.map3StringMap<Integer>MapIntegerClassCastExceptioninstanceofstringMap3Map<String, Integer>
这是Java编译器的限制吗?ClassCastException或者是否存在这样一种情况,如果忽略警告,使用某些参数调用 map3 或 stringMap3 的方法可能会导致意外?