2013-02-28 177 views
-1

我想了解为什么这段代码不会编译。
我有一个类实现一个接口。由于某种原因,最后的方法不会编译。Java抛出与SortedSet异常

它不会简单地允许我将集合转换为集合,但确实允许它返回单个对象。

有人可以向我解释为什么这是?谢谢。

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? – 2013-02-28 21:44:02

+0

是的,对不起。测试实现ITesting – Marley 2013-02-28 21:48:05

+0

看起来像http://stackoverflow.com/questions/897935/when-do-java-generics-require-extends-t-instead-of-t-and-is-there-any-down的副本 – 2013-02-28 21:49:36

回答

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 2013-02-28 21:48:30

0

你在你的declartion有一个错字:

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

,如果你想返回ITesting的方法,或者你需要的方法应该是ITesting有返回:

SortedSet<Testing> 
0

我想你想用这个代替:

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

现在你试图返回tests,它被声明为SortedSet<Testing>而不是SortedSet<ITesting>

1

假设ITestingTesting的超级类型。 通用类型不是多态的。因此SortedSet<ITesting>不是超级类型SortedSet<Testing>多态性根本不适用于泛型类型。你可能需要使用通配符? extends ITesting作为你的返回类型。

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