0

我试图为 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);

可以通过以下方式修复:Collection flatten = ArrayUtil., HashSet>>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;
    }
4

0 回答 0