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()
?
Attaching a very good example i found on javarevisited.blogspot.in
}
Output: Comparing int array i1: [1, 2, 3, 4] and i1: [1, 2, 3, 4] Does array i1 and i2 are equal : true
Comparing int array i2: [1, 2, 3, 4] and i3: [0, 2, 3, 4] Does array i2 and i3 are equal : false
Comparing double array d1: [1.5, 2.4, 3.2, 4.0, 1.0] and d2: [1.5, 2.4, 3.2, 4.0, 1.0] Does double array d1 and d2 are equal : true
Comparing double array d2: [1.5, 2.4, 3.2, 4.0, 1.0] and d3: [0.0, 2.4, 3.2, 4.0, 1.0] Does double array d2 and d3 are same : false
Comparing two String array s1: [One, Two, Three] and s2: [One, Two, Three] Are both String array s1 and s2 are equal : true
Comparing two String array s2: [One, Two, Three] and s3: [zero, Two, Three] Are both String array s2 and s3 are equal : false
Object array o1: [one, [Ljava.lang.String;@19821f] and o2: [one, [Ljava.lang.String;@addbf1] Comparing Object Array o1 and o2 with Arrays.equals : false Comparing Object Array o1 and o2 with Arrays.deepEquals : true
If at least one of the arguments of
deepEquals
method is not an array, thenObjects.deepEquals
andObjects.equals
are same.will return
How come the "shallow"
equals
methods returnfalse
? This is because in Java, for arrays, equality is determined by object identity. In this example,firstArray
andsecondArray
are distinct objects.Doing
String[] secondArray = firstArray
instead will therefore returntrue
for all four tests.deepEquals() is used with nested arrays of arbitrary depth.
equals() is used with simple primitive data types.
For ex: