Search code examples
javaarrays2d

How to get 2D subarray from 2D array in JAVA?


Suppose I have 2D array as follow:

int[][] temp={
              {1,2,3,4},
              {5,6,7,8},
              {9,10,11,12}};

and i want to get sub-array start from X direction 1 to 2 and Y direction 1 to 2 i.e.

{6,7}
{10,11}

can anyone give me solution for above problem.


Solution

  • Here you are

        int[][] temp = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 } };
        int[][] a = new int[temp.length][];
        for (int i = 0; i < temp.length; i++) {
            a[i] = Arrays.copyOfRange(temp[i], 1, 3);
        }
        System.out.println(Arrays.deepToString(a));
    

    output

    [[2, 3], [6, 7], [10, 11]]
    

    answering your question in comment if we want to access only [[6, 7], [10, 11]]

        int[][] a = new int[2][];
        for (int i = 1, j = 0; i < 3; i++, j++) {
            a[j] = Arrays.copyOfRange(temp[i], 1, 3);
        }
    

    output

    [[6, 7], [10, 11]]