java 数组交换 - 二维数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13280583/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Array swap - 2d array
提问by TimelordViktorious
I'm working on swapping indices in a two-dimensional array. I seem to be on the right track, but it's not swapping the array in the way I want.
我正在交换二维数组中的索引。我似乎在正确的轨道上,但它没有按照我想要的方式交换阵列。
The first row's index j
needs to be swapped with row 2's index j
:
第一行的索引j
需要与第 2行的索引交换j
:
for (int j = 0; j < array.length ; j++){
int temp = array[row1][j]
array[row1][j]=array[j][row1]
array[j][row1] = temp ;
}
Any ideas on how to best approach this would be appreciated.
关于如何最好地解决这个问题的任何想法将不胜感激。
回答by mreithub
As the two-dimensional array in java is actually a array of references to other arrays, you can simply swap the references as shown below:
由于java中的二维数组实际上是对其他数组的引用的数组,你可以简单地交换引用,如下所示:
public static void swapRows(int array[][], int rowA, int rowB) {
int tmpRow[] = array[rowA];
array[rowA] = array[rowB];
array[rowB] = tmpRow;
}
/edit: edited the answer as I previously misinterpreted it**
/edit:编辑答案,因为我之前误解了它**