【问题标题】:Warning when performing cast with generic types使用泛型类型执行强制转换时发出警告
【发布时间】:2014-03-05 08:55:03
【问题描述】:

我不明白为什么在尝试执行此操作时会收到警告(未经检查的强制转换):

...
Map<? estends SomeType, SomeOtherType> map;
...
Map<SomeType, SomeOtherType> castedMap = (Map<SomeType, SomeOtherType>) map;
...

我的意思是,将 castedMap 发布到外部代码有什么危险? 这两个操作都将在运行时完美运行:

  • 使用 SomeType 类型的键从 castedMap 中获取元素
  • 使用 SomeType 类型的键将元素放入 castedMap。

我会简单地使用 @SuppressWarnings("unchecked") 来抑制警告。

【问题讨论】:

    标签: java generics


    【解决方案1】:

    尽管答案可能很无聊:当有警告时,它就不是类型安全的。就是这样。

    为什么在这个例子中可以看出它不是类型安全的:

    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();
        }
    }
    

    【讨论】:

    • 确实如此!我没有这样做的代码,所以这就是我想忽略的原因。