交换多维数组元素

时间:2020-03-12 16:07:44

标签: java arrays multidimensional-array swap

我有一个多维数组,并且有一个典型的交换函数,但是该函数适用于任何数量的维吗?例如,

public void swap(int a, int b) {
    int temp = arr[a];
    arr[a] = arr[b];
    arr[b] = temp;
}

这适用于常规数组。但是我需要交换2D数组的两个索引。我可以使用相同的函数,但仅以不同的方式调用参数吗?

示例输入:

int[][] arr = {{1}, {2}, {3}};
System.out.println(arr[0][0]);

// I am confused on
// what these parameters should be
swap(arr, arr[0][0], arr[1][0]);

System.out.println(arr[0][0]);

示例输出:

1
2

2 个答案:

答案 0 :(得分:1)

是的,有可能,我建议发送arr作为方法参数:

public static <T> void swap(T[] arr, int a, int b) {
    T temp = arr[a];
    arr[a] = arr[b];
    arr[b] = temp;
}
public static void main(String[] args) {
    int[][] a = {{1,2},{3,4}};
    swap(a,0,1);
    System.out.println(Arrays.deepToString(a));
}

在您的情况下,T解析为一维数组int[]

答案 1 :(得分:0)

您可以将此功能与4个参数一起使用:

public static void swap(int [][]t,int a, int b,int c,int d) {
    int temp = t[a][b];
    t[a][b] = t[c][d];
    t[c][d] = temp;
}
相关问题