小编blu*_*edd的帖子

取消选中强制转换为实现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
}
Run Code Online (Sandbox Code Playgroud)

这是stringMap3演员阵容的完整警告:

类型安全:未经检查强制Map<capture#3-of ?,Integer> …

java generics casting type-safety unchecked-cast

14
推荐指数
1
解决办法
1568
查看次数

标签 统计

casting ×1

generics ×1

java ×1

type-safety ×1

unchecked-cast ×1