首页 > 解决方案 > 如何输入 Collection

问题描述

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

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
}

标签: genericsjava-8covarianceinvariantspecs

解决方案


我发现我必须这样做

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

我希望我能解释一下。


推荐阅读