このコードに未チェックのキャスト警告がある理由を理解しようとしています。最初の 2 つのキャストには警告がありませんが、3 番目のキャストには警告があります。
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
クラス宣言では (ie, ) の最初の型パラメーターが指定されてMap
おり、 とキャストのString
両方で (ie, )の2 番目の型パラメーターに同じ型が使用されます。私が理解していることから、キャストがスローしない限り(チェックがあるのでスローしない限り)、有効になります。map3
StringMap<Integer>
Map
Integer
ClassCastException
instanceof
stringMap3
Map<String, Integer>
これは Java コンパイラの制限ですか? ClassCastException
または、特定の引数を指定して map3 または stringMap3 のいずれかのメソッドを呼び出すと、警告が無視された場合に予期しないエラーが発生するシナリオはありますか?