判断两个数组内容是否相等
通过这个案列巩固相关知识点
package com.company;
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[][] list1 = {
{51,25,22},
{6,1,4},
{24,54,6}
};
int[][] list2 = {
{51,22,25},
{6,1,4},
{24,54,6}
};
System.out.printf("The two arrays are %s\n",equals(list1,list2) ? "identical" : "not identical");
}
//假设m1,m2均为n*n的二维数组
public static boolean equals(int[][] m1, int[][] m2){
return equals(distinctArray(m1), distinctArray(m2));
}
//判断两个一维数组是不是严格相等
public static boolean equals(int[] list1, int[] list2){
boolean out = true;
if(list1.length != list2.length){
out = false;
}else{
for(int i = 0; i < list1.length; i++){
out = out && list1[i] == list2[i];
if(!out)
break;
}
}
return out;
}
//将二维数组逐个去除元素,排除重复后,放入一维数组 (尾部去掉元素为0), 后排序再返回
public static int[] distinctArray(int[][] m){
int distinctNumbers = 0;
int[] result = new int[m.length * m[0].length];
for(int row = 0; row < m.length; row++){
for(int column = 0; column < m[row].length; column++){
if(!isInArray(result,m[row][column])){
result[distinctNumbers++] = m[row][column];
}
}
}
int[] result1 = new int[distinctNumbers];
for(int i = 0; i < result1.length; i++){
result1[i] = result[i];
}
Arrays.parallelSort(result1);
return result1;
}
//判断一个值是否在一维数组中
public static boolean isInArray(int[] list,int key){
boolean out = false;
for(int i = 0; i < list.length; i++){
if(key == list[i]){
out = true;
break;
}
}
return out;
}
}