Creating an n-dimension Array in Java during runtime

前端 未结 2 662
清酒与你
清酒与你 2021-01-07 06:38

I have a String which contains arrays. Example:

\"[[1, 2], [4, 5], [7, 8]]\"

Now, I want to make an actual Java array out of this. I have c

相关标签:
2条回答
  • 2021-01-07 07:00

    If you are doing numeric work then you should probably use a library. For example my open source library Vectorz provides proper support for multidimensional arrays / matrices (with doubles).

    Then you can just do something like:

    INDArray m=Arrayz.parse("[[1, 2], [4, 5], [7, 8]]");
    

    The INDArray object encapsulates all the multidimensionality so you don't need to worry about writing big nested loops all the time, plus it provides a lot of other functions and capabilities that normal Java arrays don't have.

    0 讨论(0)
  • 2021-01-07 07:15

    The main problem is that you can't reference an N dimensional array in code directly.

    Fortunately java has a bit of a dirty hack that lets you have some way to work with N dimensional arrays:

    Arrays are objects like every other non-primative in java.

    Therefore you can have:

    // Note it's Object o not Object[] o
    Object o = new Object [dimensionLengh];
    

    You can use a recursive method to build it up.

    Object createMultyDimArray(int [] dimensionLengths) {
        return createMultyDimArray(dimensionLengths, 0);
    }
    
    Object createMultyDimArray(int [] dimensionLengths, int depth) {
        Object [] dimension = new Object[dimensionLengths[depth]];
        if (depth + 1 < dimensionLengths.length) {
            for (int i=0; i < dimensionLengths[depth]; i++) {
                dimension[i] = createMultyDimArray(dimensionLengths, depth+1);
            }
        }
        return dimension;
    }
    

    To use this you will need to cast from Object to Object [].

    Java is type safe on arrays and mistakes can cause a ClassCastException. I would recommend you also read about how to create arrays using java reflection: http://docs.oracle.com/javase/tutorial/reflect/special/arrayInstance.html.

    0 讨论(0)
提交回复
热议问题