当我尝试执行此操作时,我不明白为什么会收到警告(未经检查的演员):
...
Map<? estends SomeType, SomeOtherType> map;
...
Map<SomeType, SomeOtherType> castedMap = (Map<SomeType, SomeOtherType>) map;
...
我的意思是将castedMap发布到外部代码有什么危险? 两种操作都可以在运行时完美地运行:
我只是使用@SuppressWarnings(“未选中”)来抑制警告。
答案 0 :(得分:4)
尽管答案可能很无聊:当有警告时,它不是类型安全的。就是这样。
为什么它不是类型安全的,在这个例子中可以看到:
import java.util.HashMap;
import java.util.Map;
class SomeType {}
class SomeSubType extends SomeType {}
class SomeOtherType {}
public class CastWarning
{
public static void main(String[] args)
{
Map<SomeSubType, SomeOtherType> originalMap = new HashMap<SomeSubType, SomeOtherType>();
Map<? extends SomeType, SomeOtherType> map = originalMap;
Map<SomeType, SomeOtherType> castedMap = (Map<SomeType, SomeOtherType>) map;
// Valid because of the cast: The information that the
// key of the map is not "SomeType" but "SomeSubType"
// has been cast away...
SomeType someType = new SomeType();
SomeOtherType someOtherType = new SomeOtherType();
castedMap.put(someType, someOtherType);
// Valid for itself, but causes a ClassCastException
// due to the unchecked cast of the map
SomeSubType someSubType = originalMap.keySet().iterator().next();
}
}