java - 如何在java中使用Arrays.equals()比较对象数组?

标签 java arrays oop object

在此示例中展示了如何执行此操作:

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 of Objects 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 objects e1 and e2 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 are null.

这几乎解释了一切。在您的情况下,第一个输出是 false因为stud1stud2Student 的实例不相等。在第二种情况下,两个数组具有相同的对象,因此测试为相等。在第三种情况下,stud1stud3是同一个对象,因此也相等。

唯一有趣的情况是 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/

相关文章:

Java 有界类型参数

C++ |无效*数据[1000]

python - 如果第二个元素不是重复的,则删除二维 numpy 数组的行

java - 变更传播规则和影响分析

php - 在 PHP 中扩展类 - 奇怪的行为

javascript - 内置类的子类的私有(private)字段在被覆盖的方法中是否不可访问?

java - 对文本文件中的值求和并打印它们

java - 如何使用 Java 以编程方式测试 WSDL 的可用性

java - 将 boolean 值序列化为 "1"和 "0"而不是 "true"和 "false"

c - JNI : create an jobjectArray without knowing the size in advance