Getting unknown number of dimensions from a multidimensional array in Java

前端 未结 5 1582
天命终不由人
天命终不由人 2020-12-18 05:23

Is it possible in Java to find the number of dimensions of an array with an \'a priori\' unknown number of dimensions? That is, if one doesn\'t know the number of dimensions

5条回答
  •  醉梦人生
    2020-12-18 05:46

    What I can suggest you is to manage this issue by using an array with only one dimension. Suppose to have N dimensions of sizes:

    size of the N dimensions

    Then you can define the size of your array as:

       int size = S_0*S_1*...*S_N-1;
    

    Then you will initialize it, for instance for an array of integers:

    int[] array = new int[size];
    

    Then to refer to an item of the array (to read or write it), you have N indexes (because of N dimensions):

    indexes to refer the array

    What you need now is a way to transform this N indexes, in one single value that can be used as an index in the one-dimensional array, the generic formula is:

    how transform the N indexes in one index for the one-dimensional array

    Basically this formula 'skips' the correct number of previous dimensions and points to the right location. This formula can be simply implemented in methods like

    int read(int[] array, int[] indexes);
    void write(int[] array, int[] indexes, int values);
    

    in order to keep the code readable. You may also implement this technique using a generic type, so the methods might work for any type.

提交回复
热议问题