2014-03-05 36 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