我试图为Java提出一个很好的类似scala的flatten方法,但在类型中迷失了:
public static <T, IC extends Collection<T>, OC extends Collection<IC>> IC flatten(OC values) {
IC result = (IC) new HashSet<T>();
for (Collection<T> value : values) {
result.addAll(value);
}
return result;
}
这在1.6中有效(有警告),但在1.7中我得到:
error: invalid inferred types for T,IC; inferred type does not conform to declared bound(s)
inferred: Set<AffiliationRole>
bound(s): Collection<Object>
where T,IC,OC are type-variables:
T extends Object declared in method <T,IC,OC>flatten(OC)
IC extends Collection<T> declared in method <T,IC,OC>flatten(OC)
OC extends Collection<IC> declared in method <T,IC,OC>flatten(OC)
更新:
在1.7中产生编译错误的实际代码:
HashSet<Collection<String>> lists = new HashSet<Collection<String>>();
Collection<String> flatten = ArrayUtil.flatten(lists);
可以用以下方法修复: 集合flatten = ArrayUtil。,HashSet&gt;&gt; flatten(lists);
尽管在assylias的评论中有一个(更好)的解决方案:
public static <T> Collection<T> flatten(Collection<? extends Collection<T>> values) {
Collection<T> result = new HashSet<T>();
for (Collection<T> value : values) {
result.addAll(value);
}
return result;
}