如果两个二维数组m1和m2具有相同的内容,则它们是相同的。编写一个方法,如果m1和m2相同的话,返回true。使用下面的方法头:
public static boolean equals(int[][] m1, int[][] m2)
编写一个测试程序,提示用户输入两个3*3的整数数组,显示两个矩阵是否相同。
package pack2;
import java.util.Arrays;
import java.util.Scanner;
public class SameArrays {
public static void main(String[] args) {
sameArrays();
}
public static void sameArrays() {
try(Scanner input = new Scanner(System.in);) {
System.out.print("Enter the size of two arrays for the length " +
"of row and column: ");
int size = input.nextInt();
int[][] list1 = new int[size][size];
int[][] list2 = new int[size][size];
System.out.print("Enter list1: ");
inputData(input, list1);
System.out.print("Enter list2: ");
inputData(input, list2);
System.out.println("The two arrays are " + (equals(list1, list2) ? "" :
"not ") + "identical");
}
}
/**接收数据输入*/
public static void inputData(Scanner input, int[][] m) {
for (int i = 0; i < m.length; i++)
for (int j = 0; j < m[i].length; j++)
m[i][j] = input.nextInt();
}
/**两个数组是否严格相同?*/
public static boolean equals(int[][] m1, int[][] m2) {
int[] temp1 = new int[m1.length * m1.length]; //m1的临时数组
int[] temp2 = new int[m2.length * m2.length]; //m2的临时数组
for (int i = 0, k = 0; i < m1.length; i++) //循环将m1、m2赋给temp1、temp2
for (int j = 0; j < m1[i].length; j++) { //由二维转换为一维
temp1[k] = m1[i][j];
temp2[k++] = m2[i][j];
}
Arrays.sort(temp1); //临时数组排序
Arrays.sort(temp2);
//调用Arrays方法
return Arrays.equals(temp1, temp2);
}
}