我正在尝试对数组m1进行排序并将其打印
import java.util.Arrays;
public class Foo {
public static void main(String[] args) {
int[][] m1 = { { 14, 11, 13, 12 },
{ 18, 15, 13, 13 },
{ 19, 16, 15, 17 } };
int[][] temp = m1.clone();
sortRows(m1);
displayArray(m1);
m1 = temp;
}
public static int[][] sortRows(int[][] m) {
for (int i = 0; i <= 2; i++) {
Arrays.sort( m[i] );
}
return m;
}
public static void displayArray(int[][] m) {
//method to print array
}
}
如何在main方法中删除数组重复并恢复原始数据?我想将它移到SortArrays方法
答案 0 :(得分:3)
多维数组中的每个数组(使用Java)也是Object
,因此您需要对每个数组执行深层复制。如果我理解你的问题,你可以做类似
public static void main(String[] args) {
int[][] m1 = { { 14, 11, 13, 12 }, { 18, 15, 13, 13 },
{ 19, 16, 15, 17 } };
int[][] temp = new int[m1.length][]; // <-- a new array for the copies.
for (int i = 0; i < m1.length; i++) {
temp[i] = m1[i].clone(); // <-- copy each row.
Arrays.sort(temp[i]); // <-- sort each row.
}
System.out.println("Original: " + Arrays.deepToString(m1));
System.out.println("Sorted copy: " + Arrays.deepToString(temp));
}
输出
Original: [[14, 11, 13, 12], [18, 15, 13, 13], [19, 16, 15, 17]]
Sorted copy: [[11, 12, 13, 14], [13, 13, 15, 18], [15, 16, 17, 19]]