0

我有一个看起来像这样的方法。

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

1 回答 1

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<>();

我希望我能解释一下。

于 2018-07-13T04:52:59.780 回答