generics - 如何输入 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
}
解决方案
我发现我必须这样做
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<>();
我希望我能解释一下。
推荐阅读
- boolean - 如何在 Coq 中编写布尔比较函数
- javascript - 通过 javascript 接收 Carrierwave URL
- arduino-uno - 可以用 Arduino Uno 转换的最大频率?
- swift - swift中的Coredata NSpredicate谓词日期
- javascript - 什么是最简单的访问方法
- 一个被点击的元素是通过 jQuery 吗?
- javascript - 如何根据搜索结果创建网站端点?
- python - 将行附加到文件并覆盖 - python
- jpa - 为什么在使用实体图查询将加载我的惰性属性之前,我必须从 EclipseLink 共享缓存中逐出我的实体?
- xamarin.android - Xamarin.Android:当我以编程方式创建按钮时,为什么它有边距?
- linux - 源文件和只执行文件有什么不同?