【问题标题】:Java cast cast exception with SortedSet带有 SortedSet 的 Java 强制转换异常
【发布时间】:2013-02-28 21:40:52
【问题描述】:

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

它不仅允许我将集合转换为集合,而且允许它很好地返回单个对象。

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

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

}

【问题讨论】:

  • 您会编辑您的问题以包含确切的编译器消息吗?编辑:另外,看起来测试实现了 ITesting?
  • 是的,对不起。测试实现 ITesting

标签: java interface casting set


【解决方案1】:

简单地说,SortedSet&lt;Testing&gt; 不是SortedSet&lt;ITesting&gt;。例如:

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

现在您的SortedSet&lt;Testing&gt; 将包含一个不是Testing 的元素。那会很糟糕。

可以做的是:

SortedSet<? extends ITesting> working = testing;

...因为那样你只能得到集合中的值out

所以这应该有效:

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

【讨论】:

  • 谢谢。这很有帮助!
【解决方案2】:

假设ITestingTesting 的超类型。 泛型类型不是多态的。因此SortedSet&lt;ITesting&gt; 不是SortedSet&lt;Testing&gt;超类型多态性根本不适用于泛型类型.您可能需要使用带有下限? extends ITesting 的通配符作为您的返回类型。

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

【讨论】:

    【解决方案3】:

    您的声明中有错字:

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

    如果您希望该方法返回一个 ITesting,或者您需要该方法返回,则应该是 ITesting:

    SortedSet<Testing>
    

    【讨论】:

      【解决方案4】:

      我想你想要这个:

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

      现在您正试图返回 tests,它被声明为 SortedSet&lt;Testing&gt; 而不是 SortedSet&lt;ITesting&gt;

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-01-22
        • 1970-01-01
        • 2019-04-05
        • 2023-03-19
        相关资源
        最近更新 更多