How to convert nested List into multidimensional array?

喜你入骨 提交于 2019-12-04 18:56:13

To create any kind of non-Object array, you need to pass a type key to the toArray method. This is because for generic types (e.g., ArrayList), the type argument is erased (so, at runtime, ArrayList<String> is treated as a plain ArrayList), whereas for arrays, the type is not.

It seems you already have the Object array creation sorted, so with that and the use of the type key, I think you're all sorted! :-)

This is the way that someone suggested to solved for String type. Cast2(List<?>) returns the multidimensional array. It may be generalized to use the class type as parameter. Thank you for your comments.

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

hehe, heres a answer too but i dunno if that really helps:

List<ArrayList<ArrayList<ArrayList<String>>>> x = new ArrayList<ArrayList<ArrayList<ArrayList<String>>>>();

    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);

    }

this prints: [[[[Ljava.lang.String;@4e82701e

looks pretty messy but i love reflections :)

You can use transmorph :

ArrayList<ArrayList<ArrayList<ArrayList<String>>>> arrayList = new ArrayList<ArrayList<ArrayList<ArrayList<String>>>>();

/// populate the list ...
[...]    

Transmorph transmorph = new Transmorph(new DefaultConverters());
String[][][][] array = transmorph.convert(arrayList, String[][][][].class);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!