如何键入Collection <!-?超级一些->?

时间:2018-07-13 04:48:56

标签: generics java-8 covariance invariants pecs

我有一个像这样的方法。

public void some(..., Collection<? super Some> collection) {
    // WOOT, PECS!!!
    final Stream<Some> stream = getStream();
    stream.collect(toCollection(() -> collection));
}

如何使该方法安全地返回给定集合实例的类型?

我尝试过这个。

public <T extends Collection<? super Some>> T some(..., T collection) {
    final Stream<Some> stream = getStream();
    stream.collect(toCollection(() -> collection)); // error.
    return collection; // this is what I want to do
}

1 个答案:

答案 0 :(得分:0)

我发现我必须这样做

public <T extends Collection<Some>> T some(..., T collection) {
    final Stream<Some> stream = getStream();
    stream.collect(toCollection(() -> collection));
    return collection; // this is what I want to do
}

这样我就可以做到

List<Some> list = some(..., new ArrayList<>();

我希望我能解释一下。