简体   繁体   中英

how can I decide the dimension of an array according to the input in Java

For example, I have an input N(you don't know until running time), and I want to build an array with N dimensions.

I cannot define the number of dimensions when I write my code like when we generally build a four-dimensional array:

int [][][][] array = new int[3][3][3][3].  

I need this array because the dimension I need to store the input is flexible, which means you cannot know the dimension until someone input it at running time.

And what's more, after I built this array, how can I have access to it? I cannot handle it as usual like

array[1][2][3][4] = 5

because I don't know the number of dimension when I write my code.

How can I reach my aim?

Probably you don't want to do that. There's almost certainly a better way to deal with whatever it is you're trying to do. However, here's an example that might help.

public class Arr {
        public static void main(String[] args)
        {
                int n = 7;
                int [][][][] foo = new int [n][n][n][n];
                foo[1][2][3][4] = 5;
                System.out.println(foo[1][2][3][4]);
        }

}

EDIT: Ah! I understand now. You want the user to input N and get an array of N dimensions, not to set the scale of the dimensions. That's tricky. You can fake it by making an array of length d1*d2*...*dN. For example, a 2D array of 3X4 is transparently a 1D array of 12, and a 3X4X5 array is just an array of 60. You'd want to write a class to handle all of this - there's a bit of work required, and you won't get the syntactic sugar of bracket notation, but it's doable.

do you need something like this??

static Object[] getNArray(int n) {
    Object[] arr = new Object[n];
    for (int i = 0; i < n-1; i++) {
        arr[i] = getNArray(n - 1);
    }
    return arr;
}

public static void main(String[] args) {
    Object[] arr = getNArray(1);
    System.out.println(arr);

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM