本文介绍了如何从JAVA中的2D数组获取2D子数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我具有2D数组,如下所示:
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]]
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);
}
输出
[[6, 7], [10, 11]]
这篇关于如何从JAVA中的2D数组获取2D子数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!