2013-02-28 3 views
-1

이 코드가 컴파일되지 않는 이유를 이해하려고합니다.
인터페이스를 구현하는 클래스가 있습니다. 마지막 방법은 어떤 이유로 컴파일되지 않습니다.SortedSet을 사용한 Java 캐스트 캐스트 예외

단순히 세트를 세트로 캐스트 할 수 없지만 단일 오브젝트를 올바르게 반환 할 수 있습니다.

누군가이 사실을 설명해 주시겠습니까? 감사.

public class Testing2 { 

    public SortedSet<ITesting> iTests = new TreeSet<ITesting>(); 
    public SortedSet<Testing> tests = new TreeSet<Testing>(); 

    public ITesting iTest = null; 
    public ITesting test = new Testing(); 

    // Returns the implementing class as expected 
    public ITesting getITesting(){ 
     return this.test; 
    } 

    // This method will not compile 
    // Type mismatch: cannot convert from SortedSet<Testing> to SortedSet<ITesting> 
    public SortedSet<ITesting> getITests(){ 
     return this.tests; 
    } 

} 
+0

정확한 컴파일러 메시지를 포함하도록 질문을 편집 하시겠습니까? 편집 : 또한 테스트는 ITesting을 구현하는 것처럼 보입니까? –

+0

예, 죄송합니다. 테스트는 ITesting을 구현합니다 – Marley

+0

http://stackoverflow.com/questions/897935/when-do-java-generics-require-extends-t-instead-of-t-and-is-there-any-down의 복제본처럼 보입니다. –

답변

6

간단하게하는 SortedSet<Testing>SortedSet<ITesting> 없습니다. 예를 들어 :

SortedSet<Testing> testing = new TreeMap<Testing>(); 
// Imagine if this compiled... 
SortedSet<ITesting> broken = testing; 
broken.add(new SomeOtherImplementationOfITesting()); 

는 이제 SortedSet<Testing>Testing하지 않은 요소가 포함됩니다. 그건 나쁠거야. 다음은 세트의에서 값을 을 얻을 수 있기 때문에 ...

SortedSet<? extends ITesting> working = testing; 

: 당신이 할 수 무엇

이있다.

그래서이 작동합니다 :

public SortedSet<? extends ITesting> getITests(){ 
    return this.tests; 
} 
+0

감사합니다. 이것은 도움이되었다! – Marley

0

당신은 당신의 declartion에 오타가 있습니다

public SortedSet<Testing> tests = new TreeSet<Testing>(); 

당신이 ITesting를 반환하는 방법을 원하거나 방법을 필요로하는 경우가 ITesting해야 하는가 다음으로 돌아 가기 :

SortedSet<Testing> 
0

을 내가 대신이 원하는 생각 :

public SortedSet<Testing> getTests(){ 
    return this.tests; 
} 

지금 당신은 SortedSet<Testing>하지 SortedSet<ITesting>로 선언 tests을 반환하려는.

1

ITestingTesting의 수퍼 유형입니다. 일반 유형은 다형성이 아닙니다. SortedSet<ITesting>수퍼 유형SortedSet<Testing>이 아닙니다. 다형성은 제네릭 유형에만 적용되지 않습니다. 당신은 반환 유형으로 lowerbounds와 함께 와일드 카드를 사용해야 할 것입니다 (? extends ITesting).

public SortedSet<? extends ITesting> getITests(){ 
    return this.tests; 
}