请建议一些优雅的转换方式 Java中数组数组到集合集合,反之亦然。
我认为Java API中没有便捷方法,对吧?
public static <T> T[][] nestedCollectionsToNestedArrays(
Collection<? extends Collection<T>> source){
// ... ?
}
public static <T> Collection<Collection<T>> nestedArraysToNestedCollections(
T[][] source){
// ... ?
}
其他问题:
什么是基本类型的嵌套数组?
我是否必须为每种基本类型声明方法,因为 禁止通用数组创建?
答案 0 :(得分:1)
收集集 - &gt;数组数组:(它只返回一个Object [] [],因为“T”的类型信息不存在。如果你想让数组成为正确的类型,你必须手动传入T的类,并且它会更复杂)
public static Object[][] nestedListsToNestedArrays(
Collection<? extends Collection<?>> source){
Object[][] result = new Object[source.size()][];
int i = 0;
for (Collection<?> subCollection : source) {
result[i++] = subCollection.toArray();
}
return result;
}
其他问题:有什么用 嵌套的基本类型数组?我 必须为每个声明方法 原始类型,
是的,您可以为每种基本类型声明方法,也可以使用反射和牺牲类型安全。原因是每个原始数组类型都是不相关的,除了Object之外,所有原始数组类型都没有超类型。
因为禁止的通用数组 创建
不,但这是另一个问题的原因:为什么收集集合 - &gt;返回T [] []的数组数组很难。
答案 1 :(得分:0)
这是array-&gt; Collection的方法:
public static <T> Collection<Collection<T>>
nestedArraysToNestedCollections(T[][] source) {
Collection<Collection<T>> ret = new ArrayList<Collection<T>>();
for (int i = 0; i < source.length; i++) {
// could be ret.add(new ArrayList<T>(Arrays.asList(source[i]));
Collection<T> list = new ArrayList<T>(source[i].length);
for (int j = 0; j < source[i].length; j++) {
list.add(source[i][j]);
}
}
return ret;
}
另一个方向比较棘手。