Method description says:
Returns true if the arguments are deeply equal to each other and false otherwise... Equality is determined by using the equals method of the first argument.
Which (to me) suggests that Objects are deeply equal if every object they maintain references to are also equal using the equals() method. And every objects they have a reference to are also equal. And ..
So .. equality is determined by using the equals method of the first argument.
How is this different from .equals()
? Assuming that we describe equals appropriately where, objects is equal to another object is every field of the object is equal to it as well.
Can you please provide an example illustrating the difference between Objects.deepEquals()
and Objects.equals()
?
equals() and deepEquals() Method to Compare two Arrays in Java. Arrays. equals() method does not compare recursively if an array contains another array on other hand Arrays. deepEquals() method compare recursively if an array contains another array.
deepEquals() in Java. Arrays. deepEquals() is used to check whether two arrays of single dimensional or multi-dimensional arrays are equal or not. It can compare two nested arrays (i.e. multidimensional array), irrespective of its dimension.
equals() method. The major difference between the == operator and . equals() method is that one is an operator, and the other is the method. Both these == operators and equals() are used to compare objects to mark equality.
equals() method in Java. Both equals() method and the == operator are used to compare two objects in Java. == is an operator and equals() is method. But == operator compares reference or memory location of objects in a heap, whether they point to the same location or not.
String[] firstArray = {"a", "b", "c"};
String[] secondArray = {"a", "b", "c"};
System.out.println("Are they equal 1 ? " + firstArray.equals(secondArray) );
System.out.println("Are they equal 2 ? " + Objects.equals(firstArray, secondArray) );
System.out.println("Are they deepEqual 1? " + Arrays.deepEquals(firstArray, secondArray) );
System.out.println("Are they deepEqual 2? " + Objects.deepEquals(firstArray, secondArray) );
will return
Are they equal 1 ? false
Are they equal 2 ? false
Are they deepEqual 1? true
Are they deepEqual 2? true
How come the "shallow" equals
methods return false
? This is because in Java, for arrays, equality is determined by object identity. In this example, firstArray
and secondArray
are distinct objects.
Doing String[] secondArray = firstArray
instead will therefore return true
for all four tests.
If at least one of the arguments of deepEquals
method is not an array, then Objects.deepEquals
and Objects.equals
are same.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With