In Java I want to convert a nested List
which contains at the deepest level a uniform type into an multidimensional array of that type. For example, ArrayList<ArrayList<ArrayList<ArrayList<String>>>>
into String[][][][]
. I've tried several things and I only can obtain an array of objects like Object[][][][]
. For 'simple lists' it seems that Apache Commons Lang does the work but I cannot figure out for nested cases.
Update:
In order to obtain a multidimensional array of Object type I'm using a recursive function so I cannot set the key type using toArray() see excerpt:
// 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;
}