Java Arrays.deepEquals()
方法
原文:https://www.studytonight.com/java-util/java-arrays-deepequals-method
在本教程中,我们将在Arrays
课中学习deepEquals()
方法。该方法与equals()
方法略有不同,因为该方法适用于一维和多维数组。
句法
public static boolean deepEquals(Object[] o1, Object[] o2)
只有在以下情况下,此方法才会返回 true:
- 数组 1 和数组 2 都是对象引用类型的数组,
Arrays.deepEquals(array1, array2)
将返回真。 - 数组 1 和数组 2 是相同原始类型的数组,适当重载
Arrays.equals(array1, array2)
将返回真。 - 排列 1 == 排列 2
- array1.equals(array2) 将返回 true。
使用 deepEquals()方法检查两个数组是否相等的示例
在下面给出的例子中,我们比较了两个嵌套数组deepEquals()
方法从数组 1 到数组 2 检查每个数组元素,也检查嵌套元素。最后,它将根据示例返回 true 或 false。在我们的例子中,两个数组不相等,所以它返回一个错误的值。
import java.util.Arrays;
class StudyTonight {
public static void main(String args[])
{
int array1[][] = {
{ 5, 2 },
{ 9, 12 },
{ 9, 1 } };
int array2[][] = {
{ 47, 8 },
{ 12, 50 },
{ 13, 14 } };
if(Arrays.deepEquals(array1, array2))
{
System.out.println("Both arrays are equal");
}
else
{
System.out.println("Both arrays are not equal");
}
}
}
两个数组不相等
示例:deepEquals()方法检查对象数组的相等性
在下面给出的例子中,我们说明了 deepEquals()
方法也可以用来检查一个对象的两个数组是否相等。在应用此方法时,我们需要特别注意覆盖 equals 方法,因为编译器应该根据哪些参数来决定两个对象是否相等。
import java.util.Arrays;
class Student
{
String stud_name;
int roll_no;
Student(String stud_name, int roll_no){
this.stud_name = stud_name;
this.roll_no = roll_no;
}
//overrifing equals method
public boolean equals(Object obj)
{
Student s = (Student)obj;
return (this.stud_name == s.stud_name && this.roll_no==s.roll_no);
}
}
class StudyTonight {
public static void main(String args[])
{
Student array1[][] = {
{ new Student("AAA",123), new Student("BBB",789) },
{ new Student("CCC",183), new Student("DDD",445) },
{ new Student("EEE",693), new Student("FFF",348) } };
Student array2[][] = {
{ new Student("AAA",123), new Student("BBB",789) },
{ new Student("CCC",183), new Student("DDD",445) },
{ new Student("EEE",693), new Student("FFF",348) } };
if(Arrays.deepEquals(array1, array2))
{
System.out.println("Both arrays are equal");
}
else
{
System.out.println("Both arrays are not equal");
}
}
}
两个数组相等
结论
在本教程中,我们学习了如何使用deepEquals()
方法比较数组。deepEquals()
方法不同于equals()
方法,因为该方法既适用于嵌套数组,也适用于对象数组。在对象数组的情况下,我们需要覆盖equals()
方法,以便编译器知道对象相等的标准。