How to store a 2d Array in another 2d Array in java?

Java 8Object Oriented ProgrammingProgramming

Create an array to which you want to store the existing array with the same length. A 2d array is an array of one dimensional arrays therefore, to copy (or, to perform any operation on) the elements of the 2d array you need two loops one nested within the other. Where, the outer loop is to traverse through the array of one dimensional arrays and, the inner loop is to traverse through the elements of a particular one dimensional array.

Example

public class Copying2DArray {
   public static void main(String args[]) {
      int[][] myArray = {{41, 52, 63}, {74, 85, 96}, {93, 82, 71} };
      int[][] copyArray =new int[myArray.length][];
      for (int i = 0; i < copyArray.length; ++i) {
         copyArray[i] = new int[myArray[i].length];
         for (int j = 0; j < copyArray[i].length; ++j) {
            copyArray[i][j] = myArray[i][j];
         }
      }
      System.out.println(Arrays.deepToString(copyArray));
   }
}

Output

[[41, 52, 63], [74, 85, 96], [93, 82, 71]]
raja
Published on 09-Jan-2018 09:40:57
Advertisements