java.util.Arrays类的equals()方法
* 类加载
import java.util.Arrays;
* 判断一维数组元素相等的方法
static boolean equals(type[] a, type[] b): 如果两个数则大小相同并且下标相同的元素都对应相等,返回true
int[] ary = {1,2,3,4,5,6};
int[] ary1 = {1,2,3,4,5,6};
int[] ary2 = {1,2,3,4};
System.out.println("数组ary是否与数组ary1相等? :" + Arrays.equals(ary, ary1));
System.out.println("数组ary是否与数组ary2相等? :" + Arrays.equals(ary, ary2));
注:equals()方法判断数组元素相等的方法:对于基本数据类型,直接判断对应元素的值是否相等;对于引用数据类型,根据该类的equals()方法来判断对应元素是否相等
import java.util.Arrays;
class Student{
private String s;
private int a;
public Student(String s, int a) {
this.s = s;
this.a = a;
}
}
public class Test {
public static void main(String[] args){
Student s1 = new Student("zhangsan", 19);
Student s2 = new Student("lisi", 20);
Student [] array1 = {new Student("zhangsan", 19), s2};
Student [] array2 = {s1, s2};
Student [] array3 = {s1, s2};
System.out.println(Arrays.equals(array1, array2));
System.out.println(Arrays.equals(array3, array2));
}
}
import java.util.Arrays;
class Student{
private String s;
private int a;
public Student(String s, int a) {
this.s = s;
this.a = a;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof Student) {
Student c = (Student) obj;
return a == c.a;
}
return false;
}
}
public class Test {
public static void main(String[] args){
Student s1 = new Student("zhangsan", 19);
Student s2 = new Student("lisi", 20);
Student [] array1 = {new Student("zhangsan", 19), s2};
Student [] array2 = {new Student("zhangsan", 19), s2};
System.out.println(Arrays.equals(array1, array2));
}
}
* 判断多维数组元素相等的方法
static boolean deepEquals(type[] a, type[] b)
int[][] ary1 = {{1,2}, {3,4,5}, {6}};
int[][] ary2 = {{1,2}, {3,4,5}, {6}};
System.out.println("数组ary1是否与数组ary2相等? :" + Arrays.deepEquals(ary1, ary2));