使用SortedSet的Java强制转换异常

时间:2013-02-28 21:40:53

标签: java interface casting set

我试图理解为什么这段代码无法编译 我有一个实现接口的类。最后一种方法由于某种原因无法编译。

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

有人可以向我解释为什么会这样吗?感谢。

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;
    }

}

4 个答案:

答案 0 :(得分: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>将包含 a Testing的元素。那会很糟糕。

可以做的是:

SortedSet<? extends ITesting> working = testing;

...因为那时你只能获得该组的值 out

所以这应该有效:

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

答案 1 :(得分:1)

假设ITestingTesting的超级类型。 通用类型不是多态的。因此SortedSet<ITesting>不是SortedSet<Testing>超类型多态根本不是申请通用类型。您可能需要使用带有下限? extends ITesting的通配符作为返回类型。

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

答案 2 :(得分:0)

您的声明中有拼写错误:

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

如果您希望方法返回ITesting,或者您需要返回的方法,那么应该在那里进行ITesting:

SortedSet<Testing>

答案 3 :(得分:0)

我想你想要这个:

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

现在您正在尝试返回tests,其被声明为SortedSet<Testing>而不是SortedSet<ITesting>