如何从JAVA中的二维数组获取二维子数组? [英] How to get 2D subarray from 2D array in JAVA?

查看:64
本文介绍了如何从JAVA中的二维数组获取二维子数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有如下二维数组:

Suppose I have 2D array as follow:

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

我想从X方向1到2和Y方向1到2开始子阵列,即

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.

推荐答案

你来了

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

输出

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

在评论中回答您的问题如果我们只想访问 [[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);
    }

输出

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

这篇关于如何从JAVA中的二维数组获取二维子数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆