2014-03-05 33 views
3

我不明白为什么我得到一个警告(未选中CAST)当我尝试执行此:警告进行投与泛型类型时

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

我的意思是出版castedMap对外部代码的危险?从castedMap使用类型SOMETYPE

  • 使用类型SOMETYPE的关键投入要素在castedMap的关键

    • 越来越要素: 两个opperations将完全在运行时工作。

    我会使用@SuppressWarnings简单地抑制警告( “未登记”)。

  • 回答

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

    事实上,这是真的!我没有这样的代码,所以这就是我试图忽略的原因。 – Alex