title: How to access multidimensional array programmatically in Java?
body: <p>Suppose we have multidimensional array, and the number of dimensions is known only at runtime. And suppose we have an integer number of indices.</p>
  
  <p>How to apply indices to array so to access array's element?</p>
  
  <p><strong>UPDATE</strong></p>
  
  <p>Suppose:</p>
  
  <pre><code>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
  
  ...
  </code></pre>
  
  <p>I want to fetch the element addressed by indices <code>indices</code> from <code>array</code>.</p>
  
  <p><strong>UPDATE 2</strong></p>
  
  <p>I wrote following code based on recursion:</p>
  
  <pre><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&lt;ans.length; ++i ) {
                  ans[i] = element++;
              }
          }
  
          else {
              for(int i=0; i&lt;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));
  
      }
  
  }
  </code></pre>
  
  <p>The questions are:</p>
  
  <p>1) are there any reliable ready-made methods from JDK and/or famous libraries for this?</p>
  
  <p>2) I was using <code>Object</code>. can it be avoided? can I create/access variable dimensionality array of built-in or specific type? how large is a payoff due to using <code>Object</code>?</p>