Generics 如何输入集合<;?超级一些>;?
我有一个这样的方法Generics 如何输入集合<;?超级一些>;?,generics,java-8,covariance,invariants,pecs,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 void some(…,Collection我发现我必须这样做 publ
public void some(..., Collection<? super Some> collection) {
// WOOT, PECS!!!
final Stream<Some> stream = getStream();
stream.collect(toCollection(() -> collection));
}
public void some(…,Collection我发现我必须这样做
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
}
publictsome(…,T集合){
最终流=getStream();
stream.collect(toCollection(()->collection));
return collection;//这就是我要做的
}
所以我可以这样做
List<Some> list = some(..., new ArrayList<>();
List List=some(…,new ArrayList();
我希望我能解释一下。将集合作为参数的目的是什么?比如选择何时调用方法您拥有的集合类型列表,设置,…?如果这是您的预期用例,只需使用public T some(…,Supplier s){return getStream().collect(toCollection(s));}
。然后,您可以编写List List=some(…,ArrayList::new);
.collect(toCollection(()->collection))
违反了合同,因为供应商应该在每次评估时返回一个空的新集合。在很多情况下,这可能会中断。只需使用.forEachOrdered(collection::add)
。这也可以解决编译问题。
List<Some> list = some(..., new ArrayList<>();