title: How to get the sum of two n-dimensional arrays in Java?
body: <h1>Adding two n-dimensional arrays in Java</h1>
  
  <h2>addVectors</h2>
  
  <p>Two 1-dimensional arrays / vectors in Java can be added like this:</p>
  
  <pre><code>public static int[] addVectors( int[] a, int[] b )
  {
      int[] c = new int[a.length];
  
      for ( int i = 0; i &lt; a.length; i++ )
      {
          c[i] = a[i] + b[i];
      }
  
      return c;
  }
  </code></pre>
  
  <h2>addMatrices</h2>
  
  <p>Two 2-dimensional arrays / matrices in Java can be added like this:</p>
  
  <pre><code>public static int[][] addMatrices( int[][] a, int[][] b )
  {
      int[][] c = new int[a.length][a[0].length];
  
      for ( int i = 0; i &lt; a.length; i++ )
      {
          c[i] = addVectors( a[i], b[i] );
      }
  
      return c;
  }
  </code></pre>
  
  <p>Both functions require the arrays to be of the same size to avoid an <code>arrayOutOfBoundsException</code>.</p>
  
  <h2>addArraysN</h2>
  
  <p>There should be a way to add two arrays of unknown dimension using recursion.<br>
  For example, the following code using the hypothetical function <code>addArraysN( arr1, arr2 )</code></p>
  
  <pre><code>int[][][] a = { 
                  { { 1, 1, 1 }, { 1, 1, 1 }, { 1, 1, 1 } },
                  { { 1, 1, 1 }, { 1, 1, 1 }, { 1, 1, 1 } },
                  { { 1, 1, 1 }, { 1, 1, 1 }, { 1, 1, 1 } }
                };
  int[][][] b = { 
                  { { 2, 2, 2 }, { 2, 2, 2 }, { 2, 2, 2 } },
                  { { 2, 2, 2 }, { 2, 2, 2 }, { 2, 2, 2 } },
                  { { 2, 2, 2 }, { 2, 2, 2 }, { 2, 2, 2 } }
                };
  int[][][] sum = addArraysN( a, b );
  System.out.println( java.util.Arrays.deepToString( sum ) );
  </code></pre>
  
  <p>should output</p>
  
  <pre><code>[[[3, 3, 3], [3, 3, 3], [3, 3, 3]], [[3, 3, 3], [3, 3, 3], [3, 3, 3]], [[3, 3, 3], [3, 3, 3], [3, 3, 3]]]
  </code></pre>
  
  <p>Now I'm wondering about how to implement this function <code>addArraysN( arr1, arr2 )</code>.<br>
  I started out with the following pseudo code:</p>
  
  <pre><code>addArraysN( arr1, arr2 )
  {
      int dimension = getDimension( arr1 );
      if ( dimension == 0 ) //there are no arrays, only numbers
          return arr1 + arr2;
      else
      {
          //create a new arrays with the same dimension and size as arr1 / arr2
          //loop through the fields with for
              //call itself when adding the fields of arr1 and arr2
          //return the sum
      }
  }
  </code></pre>
  
  <p>New arrays can be created using the <code>newInstance</code>-method from <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/reflect/Array.html" rel="nofollow noreferrer" title="Array &#40;Java Platform SE 7 &#41;">java.lang.reflect.Array</a>.<br>
  Looping can be made possible like this:</p>
  
  <pre><code>for ( int i = 0; i &lt; ((int[])arr1).length; i++ )
      sum = addArraysN( ((int[])arr1)[i], ((int[])arr2)[i] );
  </code></pre>
  
  <h2>Question</h2>
  
  <p>But I stumbled over a lot of runtime errors and other problems. Has anybody an idea or even a solution on how to implement this <code>addArrayN</code>-method?</p>
  
  <p>It should be also possible to work with <code>ArrayList</code> or any other Class but I'm mainly interested on how to do this with arrays... (Nevertheless if someone knows it please post!)</p>
  
  <p>Thanks in advance</p>
  
  <h2>appendix 1</h2>
  
  <p>My original code:</p>
  
  <pre><code>import java.util.Arrays;
  import java.lang.reflect.Array;
  
  public class ArrayN
  {
      public static void main( String[] args )
      {
          //Vector
          int[] vector1 = {0, 1, 2, 3, 4};
          int[] vector2 = {4, 3, 2, 1, 0};
  
          int[] vector3 = ArrayN.addVectors( vector1, vector2 );
  
          for ( int num : vector3 )
          {
              System.out.print( num );
          }
          System.out.println();
  
          System.out.println();
  
          //Matrix
          int[][] matrix1 = {{0, 1, 2, 3, 4}, {4, 3, 2, 1, 0}};
          int[][] matrix2 = {{4, 3, 2, 1, 0}, {0, 1, 2, 3, 4}};
  
          int[][] matrix3 = ArrayN.addMatrices( matrix1, matrix2 );
  
          for ( int[] vector : matrix3 )
          {
              for ( int num : vector )
              {
                  System.out.print( num );
              }
              System.out.println();
          }
  
          System.out.println();
  
          //N-Array
  
          System.out.println( Arrays.deepToString( (Object[])ArrayN.addArraysN( (Object)matrix1, (Object)matrix2, 2, 5 ) ) );
  
      }
  
      public static int[] addVectors( int[] a, int[] b )
      {
          int[] c = new int[a.length];
  
          for ( int i = 0; i &lt; a.length; i++ )
          {
              c[i] = a[i] + b[i];
          }
  
          return c;
      }
  
      public static int[][] addMatrices( int[][] a, int[][] b )
      {
          int[][] c = new int[a.length][a[0].length];
  
          for ( int i = 0; i &lt; a.length; i++ )
          {
              c[i] = ArrayN.addVectors( a[i], b[i] );
          }
  
          return c;
      }
  
      public static Object addArraysN( Object arrayN1, Object arrayN2, int dimension, int innerlength )
      {
          if ( dimension == 0 )
          {
              return (int)arrayN1 + (int)arrayN2;
          }
          else
          {
              int[] dimensions = new int[dimension];
              for ( int i = 0; i &lt; dimension; i++ )
              {
                  dimensions[i] = innerlength;
              }
              Object arrayN3 = Array.newInstance( Array.class, dimensions );
              for ( int i = 0; i &lt; Array.getLength( arrayN1 ); i++ )
              {
                  Array.set( arrayN3, i, ArrayN.addArraysN( Array.get( arrayN1, i ), Array.get( arrayN2, i ), dimension-1, innerlength ) );
              }
  
              return arrayN3;
          }
      }
  }
  </code></pre>
  
  <p>Output:</p>
  
  <pre><code>44444
  
  44444
  44444
  
  Exception in thread "main" java.lang.IllegalArgumentException: array element type mismatch
      at java.lang.reflect.Array.set(Native Method)
      at ArrayN.addArraysN(ArrayN.java:85)
      at ArrayN.addArraysN(ArrayN.java:85)
      at ArrayN.main(ArrayN.java:41)
  </code></pre>
  
  <h2>appendix 2</h2>
  
  <p>I've found the error. It was the following line:</p>
  
  <pre><code>Object arrayN3 = Array.newInstance( Array.class, dimensions );
  </code></pre>
  
  <p>I had to replace <code>Array.class</code> with <code>int.class</code>. The corrected line should be:</p>
  
  <pre><code>Object arrayN3 = Array.newInstance( int.class, dimensions );
  </code></pre>
  
  <p>Now I realized another problem the code has:<br>
  Every array in the multidimensional array has to be of the same size because of the innerlength argument. If arrays are shorter the other values become zero:</p>
  
  <pre><code>44444
  
  44444
  44444
  
  [[4, 4, 4, 4, 4], [4, 4, 4, 4, 4], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
  </code></pre>
  
  <p>So I first made <code>matrix1</code> and <code>matrix2</code> a bit longer:</p>
  
  <pre><code>//Matrix
  int[][] matrix1 = {{0, 1, 2, 3, 4}, {4, 3, 2, 1, 0}, {0, 1, 2, 3, 4}, {4, 3, 2, 1, 0}, {0, 1, 2, 3, 4}};
  int[][] matrix2 = {{4, 3, 2, 1, 0}, {0, 1, 2, 3, 4}, {4, 3, 2, 1, 0}, {0, 1, 2, 3, 4}, {4, 3, 2, 1, 0}};
  </code></pre>
  
  <p>But that's not a good solution.<br>
  Nikoloz wrote a method to find out the dimensions of arrays. Using it and another method <code>arrayToString( Object )</code> I wrote my final code is now:</p>
  
  <pre><code>import java.util.Arrays;
  import java.lang.reflect.Array;
  import java.util.List;
  import java.util.ArrayList;
  
  public class ArrayN
  {
      public static void main( String[] args )
      {
          int[][] matrix1 = {{0, 1, 2, 3, 4}, {4, 3, 2, 1, 0}};
          int[][] matrix2 = {{4, 3, 2, 1, 0}, {0, 1, 2, 3, 4}};
  
          System.out.println( ArrayN.arrayToString( ArrayN.addArraysN( matrix1, matrix2 ) ) );
  
      }
  
      public static Object addArraysN( Object arrayN1, Object arrayN2 )
      {
          ArrayList&lt;Integer&gt; dimensions = new ArrayList&lt;Integer&gt;();
          ArrayN.getDimensions( arrayN1, dimensions );
          int[] dims = new int[dimensions.size()];
          for ( int i = 0; i &lt; dims.length; i++ )
          {
              dims[i] = dimensions.get( i );
          }
  
          if ( dims.length == 0 )
          {
              return (int)arrayN1 + (int)arrayN2;
          }
          else
          {
              Object arrayN3 = Array.newInstance( int.class, dims );
              for ( int i = 0; i &lt; Array.getLength( arrayN1 ); i++ )
              {
                  Array.set( arrayN3, i, ArrayN.addArraysN( Array.get( arrayN1, i ), Array.get( arrayN2, i ) ) );
              }
  
              return arrayN3;
          }
      }
  
      public static void getDimensions( Object array, List&lt;Integer&gt; dimensions )
      {
          if ( array != null &amp;&amp; array.getClass().isArray() )
          {
              dimensions.add( Array.getLength( array ) );
              if ( Array.getLength( array ) &gt; 0)
              {
                  ArrayN.getDimensions( Array.get( array, 0 ), dimensions );
              }
          }
      }
  
      public static String arrayToString( Object arr )
      {
          if ( arr instanceof byte[] )
              return Arrays.toString( (byte[])arr );
          else if ( arr instanceof short[] )
              return Arrays.toString( (short[])arr );
          else if ( arr instanceof int[] )
              return Arrays.toString( (int[])arr );
          else if ( arr instanceof long[] )
              return Arrays.toString( (long[])arr );
          else if ( arr instanceof float[] )
              return Arrays.toString( (float[])arr );
          else if ( arr instanceof double[] )
              return Arrays.toString( (double[])arr );
          else if ( arr instanceof char[] )
              return Arrays.toString( (char[])arr );
          else if ( arr instanceof boolean[] )
              return Arrays.toString( (boolean[])arr );
          else
              return Arrays.deepToString( (Object[])arr );
      }
  }
  </code></pre>
  
  <p>Another possibility would be to take dimension 1 as the base case:</p>
  
  <pre><code>public static Object addArraysN( Object arrayN1, Object arrayN2 )
  {
      ArrayList&lt;Integer&gt; dimensions = new ArrayList&lt;Integer&gt;();
      ArrayN.getDimensions( arrayN1, dimensions );
      int[] dims = new int[dimensions.size()];
      for ( int i = 0; i &lt; dims.length; i++ )
      {
          dims[i] = dimensions.get( i );
      }
      if ( dims.length == 1 )
      {
          Object arrayN3 = Array.newInstance( int.class, dims );
          for ( int i = 0; i &lt; Array.getLength( arrayN1 ); i++ )
          {
              int sum = ((int[])arrayN1)[i] + ((int[])arrayN2)[i];
              Array.set( arrayN3, i, sum );
          }
          return arrayN3;
      }
      else
      {
          Object arrayN3 = Array.newInstance( int.class, dims );
          for ( int i = 0; i &lt; Array.getLength( arrayN1 ); i++ )
          {
              Array.set( arrayN3, i, (int[])ArrayN.addArraysN( Array.get( arrayN1, i ), Array.get( arrayN2, i ) ) );
          }
  
          return arrayN3;
      }
  }
  </code></pre>
  
  <h3>Related questions</h3>
  
  <p><a href="https://stackoverflow.com/questions/17401958/how-to-sum-arrays-in-java">How to sum arrays in Java</a><br>
  <a href="https://stackoverflow.com/questions/3104504/is-it-possible-to-dynamically-build-a-multi-dimensional-array-in-java">Is it possible to dynamically build a multi-dimensional array in Java?</a><br>
  <a href="https://stackoverflow.com/questions/2200399/iterating-over-arrays-by-reflection">Iterating over arrays by reflection</a><br>
  <a href="https://stackoverflow.com/questions/15907178/java-reflection-get-size-of-array-object">Java Reflection - Get size of array object</a><br>
  <a href="https://stackoverflow.com/questions/17565153/creating-an-n-dimension-array-in-java-during-runtime">Creating an n-dimension Array in Java during runtime</a><br>
  <a href="https://stackoverflow.com/questions/1067073/java-multidimensional-array">Initialising a multidimensional array in Java</a><br>
  <a href="https://stackoverflow.com/questions/15638550/finding-sum-of-two-dimensional-array-java">finding sum of two dimensional array java</a><br>
  <a href="https://stackoverflow.com/questions/6065808/adding-matrices-java">Adding matrices Java</a><br>
  <a href="https://stackoverflow.com/questions/13694534/java-matrices-arrays">Java Matrices Arrays</a></p>