【问题标题】:Using casting in generics in return statement在返回语句中使用泛型类型转换
【发布时间】:2012-05-28 15:07:28
【问题描述】:

我有以下课程:

public class Base {
   public int someMethod(){...}
}

public class Derrived extends Base {
   @Override
   public int someMethod(){...}
}

我还有一个返回List<Base>的方法

List<Base> method() {
   return fetch();
}

方法 fetch() 返回 List&lt;? extends Base&gt; 但实际上它包含 Derived 类的实例列表

List<? extends Base> fetch() {}

但定义方法method() 的代码将无法编译。它需要转换为List&lt;Base&gt;。如果我总是可以将该集合的实例视为基类的实例,为什么我需要强制转换它?

【问题讨论】:

    标签: java generics casting


    【解决方案1】:

    List&lt;? extends Base&gt;List&lt;Base&gt; 不同,就像一堆香蕉不是水果碗一样。

    考虑:

    List<Derived> x = new ArrayList<Derived>();
    
    // This is valid...
    List<? extends Base> y = x;
    
    // This is what you *want* to be valid
    List<Base> z = y;
    
    z.add(new Base());
    
    // This looks fine at compile-time... but what would you expect it to do?
    Derived d = x.get(0);
    

    List&lt;Derived&gt; 的所有现有 元素视为Base 的实例是一回事 - 但您不能添加 Base 到@ 987654327@>,而您可以将一个添加到List&lt;Derived&gt;。不是每个List&lt;Derived&gt; 都是List&lt;Base&gt;

    【讨论】:

    • 在我的情况下执行转换为List&lt;Base&gt; 是否是一个好的解决方案(该方法的返回类型必须为List&lt;Base&gt; 类型)?
    • @maks:不,不是。如果可以的话,最好更改方法的返回类型...
    【解决方案2】:

    您不能这样做,因为无法保证有人不会尝试将 Base 的不同子类的对象插入到 Collection 中。

    然后会发生什么?

    看起来没问题,但您基本上是在尝试在同一个集合中使用两种不同类型的对象,如您所知,这是不允许的。

    【讨论】:

      猜你喜欢
      • 2019-01-03
      • 1970-01-01
      • 2021-05-31
      • 1970-01-01
      • 1970-01-01
      • 2014-08-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多