如何输入收藏<? 超级一些>?



我有一个类似这样的方法。

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
}

我发现我必须做这个

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

我希望我能解释一下。

最新更新