경고

2014-03-05 4 views
3

이해가 안 :경고

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

내가 외부의 코드 출판 castedMap의 위험이 무엇을 의미 ? 두 opperations는 런타임에 완벽하게 작동합니다

  • 점점 요소를 castedMap에서 형 SomeType의 키를 사용하여 castedMap의 요소를 넣어 타입 SomeType
  • 의 키를 사용하여.

나는 @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