在此示例中展示了如何执行此操作:
Student[] stud1 = new Student[2];
Student[] stud2 = new Student[2];
Student[] stud3 = new Student[2];
boolean b;
stud1[0]= new Student("Johnny","Bravo");
stud1[1]= new Student("Ace","Ventura");
stud2[0]= new Student("Ash","Ketchum");
stud2[1]= new Student("Mike","Wazowski");
b = Arrays.equals(stud1,stud2);
System.out.println(b);
stud2 [0] = stud1[0];
stud2[1] = stud1[1];
b = Arrays.equals(stud1,stud2);
System.out.println(b);
stud3 = stud1;
b = Arrays.equals(stud1,stud3);
System.out.println(b);
}
结果是假真真。 Arrays.equals 到底比较什么? 谢谢。
最佳答案
直接来自the docs :
Returns
true
if the two specified arrays ofObjects
are equal to one another. The two arrays are considered equal if both arrays contain the same number of elements, and all corresponding pairs of elements in the two arrays are equal. Two objectse1
ande2
are considered equal if(e1==null ? e2==null : e1.equals(e2))
. In other words, the two arrays are equal if they contain the same elements in the same order. Also, two array references are considered equal if both arenull
.
这几乎解释了一切。在您的情况下,第一个输出是 false
因为stud1
和stud2
有 Student
的实例不相等。在第二种情况下,两个数组具有相同的对象,因此测试为相等。在第三种情况下,stud1
和stud3
是同一个对象,因此也相等。
唯一有趣的情况是 Student
有一个equals()
方法,并且您想要测试两个具有等效但不相同的数组 Student
对象:
Student[] stud1 = {
new Student("Johnny","Bravo")
};
Student[] stud2 = {
new Student("Johnny","Bravo")
};
System.out.println(Arrays.equals(stud1, stud2));
此处的输出取决于 Student.equals()
的实现.
关于java - 如何在java中使用Arrays.equals()比较对象数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41917330/