我想知道是否有办法在方法中更改2D数组的列而无需接收整个数组并对其进行修改?
public static void main(String[] args){
int[][] a = {{1,2,3},{4,5,6},{7,8,9}};
int[] b = reverse(new int[]{1,2,3});
System.out.println(Arrays.toString(b));
System.out.println(Arrays.deepToString(a));
System.out.println(Arrays.toString(new int[]{a[0][0],a[1][0],a[2][0]}));
System.out.println(Arrays.deepToString(a));
}
public static int[] reverse(int[] start)
{
int[] result = new int[start.length];
int x = 0;
for(int i= start.length-1; i >= 0; i --)
{
result[i] = start[x];
x ++;
}
return result;
}
目前,它会反转输入的数字,但不会修改a[0][0]
,a[1][0]
和a[2][0]
的位置。原始数组保持不变,但创建的新数组已修改。我该如何解决这个问题?
答案 0 :(得分:0)
您可以先对内部子数组进行排序,然后对外部父数组进行排序。
//Array for testing
int[][] a = {{1,2,3},{4,5,6},{7,8,9}};
System.out.println(Arrays.deepToString(a));
//loop through inner array only and reverse items
for (int i = 0; i < a.length; i++){
a[i] = reverse(a[i]);
}
System.out.println(Arrays.deepToString(a));
//loop through outer array only and reverse parents.
//Note that this only needs to goe through half the array that is why we use "a.length / 2".
for (int i = 0; i < a.length / 2; i++){
int[] temp = a[i];
a[i] = a[a.length - i - 1];
a[a.length - i - 1] = temp;
}
System.out.println(Arrays.deepToString(a));
输出:
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
[[3, 2, 1], [6, 5, 4], [9, 8, 7]]
[[9, 8, 7], [6, 5, 4], [3, 2, 1]]