When implementing the
equals() method we should make sure that it's:
- reflexive (x <-> x):
x.equals(x)
must return true.
- symmetric (x <-> y):
x.equals(y)
returns true if and only if y.equals(x)
returns true.
- transitive (equals()x <-> y && y <-> z => x <-> z): if
x.equals(y)
and y.equals(z)
return true, then x.equals(z)
must return true.
- consistent (either always true or always false): multiple invocations must consistently return the same result
Calling the
equals() method with
null as the argument should return
false.
Important: When overriding
equals(), you must also override
hashCode() to maintain the general contract that equal objects must have equal hash codes.
The
equals() method is defined in the
java.lang.Object class:
public boolean equals(Object obj) {
return (this == obj);
}
The
java.util.Objects class provides utility methods to check if two objects are equals or deeply equals (in case of arrays):
public static boolean equals(Object a, Object b) {
return (a == b) || (a != null && a.equals(b));
}
public static boolean deepEquals(Object a, Object b) {
if (a == b)
return true;
else if (a == null || b == null)
return false;
else
return Arrays.deepEquals0(a, b);
}
The
java.util.Arrays class provides utility methods to check if two arrays are equals
(including specific overloaded methods for each primitive type).
It also provides a utility method to check if two arrays are deeply equals (nested arrays).