Suppose we have a multidimensional array, and the number of measurements is known only at runtime. And suppose we have an integer number of indices.
How to apply indexes to an array to access an array element?
UPDATE
Let's pretend that:
int [] indices = new int { 2, 7, 3, ... , 4}; // indices of some element int X = indices.length; // number of dimensions Object array = .... // multidimensional array with number of dimensions X ...
I want to get the element addressed by indices indices from array .
UPDATE 2
I wrote the following recursion based code:
package tests; import java.util.Arrays; public class Try_Multidimensional { private static int element; public static int[] tail(int[] indices) { return Arrays.copyOfRange(indices, 1, indices.length); } public static Object[] createArray(int ... sizes) { Object[] ans = new Object[sizes[0]]; if( sizes.length == 1 ) { for(int i=0; i<ans.length; ++i ) { ans[i] = element++; } } else { for(int i=0; i<ans.length; ++i) { ans[i] = createArray(tail(sizes)); } } return ans; } public static Object accessElement(Object object, int ... indices) { if( object instanceof Object[] ) { Object[] array = (Object[]) object; return accessElement(array[indices[0]], tail(indices)); } else { return object; } } public static void main(String[] args) { element = 0; Object array = createArray(4, 5, 12, 7); System.out.println(accessElement(array, 0, 0, 0, 0)); System.out.println(accessElement(array, 0, 0, 0, 1)); System.out.println(accessElement(array, 1, 0, 10, 0)); try { System.out.println(accessElement(array, 0, 5, 0, 1)); } catch(Exception e) { System.out.println(e.toString()); } System.out.println(4*5*12*7-1); System.out.println(accessElement(array, 3, 4, 11, 6)); } }
Questions:
1) Are there reliable ready-made methods from the JDK and / or well-known libraries for this?
2) I used Object . can it be avoided? can I create / access an array of variable dimension of built-in or specific type? how big is the gain due to using Object ?