如何将嵌套List转换为多维数组?
在Java中,我想将嵌套的List
转换为该类型的多维数组,该List
包含最深层次的统一类型。 例如, ArrayList<ArrayList<ArrayList<ArrayList>>>
进入String[][][][]
。 我尝试了几件事,我只能获得像Object[][][][]
这样的Object[][][][]
数组。 对于“简单列表”,似乎Apache Commons Lang完成了这项工作,但我无法弄清楚嵌套案例。
更新:
为了获得Object类型的多维数组,我使用了递归函数,所以我无法使用toArray()设置密钥类型,请参阅摘录:
// the argument of this function is a (nested) list public static Object convert(Object object) { Object[] result = null; List list = (List) object; if (list != null) { Object type = getElementType(list); if (type instanceof List) { int size = list.size(); result = new Object[size]; for (int counter = 0; counter < size; counter++) { Object element = list.get(counter); result[counter] = (element != null) ? convert(element) : null; } } else { result = list.toArray(); } } return result; } private static Object getElementType(List list) { Object result = null; for (Object element : list) { if (element != null) { result = element; break; } } return result; }
要创建任何类型的非Object
数组,您需要将类型键传递给toArray
方法。 这是因为对于generics类型(例如, ArrayList
),类型参数被擦除 (因此,在运行时, ArrayList
被视为普通的ArrayList
),而对于数组,类型不是。
看来你已经对Object
数组的创建进行了排序,所以使用它并使用了类型键,我想你们都已整理好了! 🙂
这是有人建议解决String
类型的方式。 Cast2(List>)
返回多维数组。 可以推广使用类类型作为参数。 谢谢您的意见。
static int dimension2(Object object) { int result = 0; if (object instanceof List>) { result++; List> list = (List>) object; for (Object element : list) { if (element != null) { result += dimension2(element); break; } } } return result; } static Object cast2(List> l) { int dim = dimension2(l); if (dim == 1) { return l.toArray(new String[0]); } int[] dims = new int[dimension2(l)]; dims[0] = l.size(); Object a = Array.newInstance(String.class, dims); for (int i = 0; i < l.size(); i++) { List> e = (List>) l.get(i); if (e == null) { Array.set(a, i, null); } else if (dimension2(e) > 1) { Array.set(a, i, cast2(e)); } else { Array.set(a, i, e.toArray(new String[0])); } } return a; }
嘿嘿,这也是一个答案,但我不知道如果真的有帮助:
List>>> x = new ArrayList>>>(); public static void main(String[] args) throws MalformedURLException, IOException, SecurityException, NoSuchFieldException { Type t = ((ParameterizedType)(jdomTEst.class.getDeclaredField("x").getGenericType())).getActualTypeArguments()[0]; int[] dims = new int[t.toString().split("List").length]; Object finalArray = Array.newInstance(String.class, dims); System.out.println(finalArray); }
这打印:[[[[[Ljava.lang.String; @ 4e82701e
看起来很乱,但我喜欢思考:)
你可以使用transmorph :
ArrayList>>> arrayList = new ArrayList>>>(); /// populate the list ... [...] Transmorph transmorph = new Transmorph(new DefaultConverters()); String[][][][] array = transmorph.convert(arrayList, String[][][][].class);