Java泛型挑战

描述

首先,下面显示了所有要复制的代码以及该实现的UML图。我知道我所使用的名称可能会造成混淆,但是对于我手头的这个最小的工作示例,我无法提出更好的建议。

The essence of the problem is in class AChildOne and is related to these three lines of code:

List<C<B>> cBList = new ArrayList<>();
List<C<BChild>> cBChildList = aChildTwo.get();
cBList.addAll(cBChildList);  // <-- COMPILATION ERROR

如果我将上述代码片段的第一行更改为:

List<C<? extends B>> cBList = new ArrayList<>();

特定的编译错误消失了,但它破坏了该类的其他部分。

If I remove the container class C from this implementation, things seem to work. However, in the actual implementation it does a bit more than what is shown in this minimal example so it is not so easy to remove it.

我当时想我想做这样的事情:

public class AChildOne implements A<? extends B>

但这是不允许的。

I suppose the problem is that I'm not able to successfully combine the generics for the return value of AChildOne::get() with the return value of AChildTwo::get().

我怀疑我在这里试图做的是泛型的那些“陷阱”之一,不允许您这样做。

UML图

uml diagram

import java.util.List;

public interface A<T> {
  List<C<T>> get();
}

import java.util.ArrayList;
import java.util.List;

public class AChildOne implements A<B> {

  private final AChildTwo aChildTwo = new AChildTwo();

  public List<C<B>> get() {
    List<C<B>> cBList = new ArrayList<>();
    List<C<BChild>> cBChildList = aChildTwo.get();

    cBList.addAll(cBChildList);  // <-- COMPILATION ERROR

    return cBList;
  }
}
import java.util.ArrayList;
import java.util.List;

public class AChildTwo implements A<BChild> {
  List<C<BChild>> list = new ArrayList<>();

  public List<C<BChild>> get() {
    return list;
  }
}
public class B {
}
public class BChild extends B {
}
public class C<T> {
  T value;

  T get() {
    return value;
  }
}
评论