私は 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;
}