How to access multidimensional array programmatically in Java? -


suppose have multidimensional array, , number of dimensions known @ runtime. , suppose have integer number of indices.

how apply indices array access array's element?

update

suppose:

int [] indices = new int { 2, 7, 3, ... , 4}; // indices of element int x = indices.length; // number of dimensions object array = .... // multidimensional array number of dimensions x  ... 

i want fetch element addressed indices indices array.

update 2

i wrote following code based on recursion:

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

the questions are:

1) there reliable ready-made methods jdk and/or famous libraries this?

2) using object. can avoided? can create/access variable dimensionality array of built-in or specific type? how large payoff due using object?

int index(object arraytoindex, int... indices) {     (int = 0; < indices.length - 1; i++) {         arraytoindex = ((object[]) arraytoindex)[indices[i]];     }     return ((int[]) arraytoindex)[indices[indices.length-1]]; } 

loop through dimensions , index each dimension, 1 @ time. casts , special case last dimension going annoying, recommend wrapping in sort of n-dimensional array class. (it looks options exist.)


Comments

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

Python ctypes access violation with const pointer arguments -