Java provides way to define comparison of object outside scope Object using Comparator
.
Now my questions is why java does not allow do same for equals() and hashcode().
Now each collection contains()
method can easily use this external equality provider to check objects are equal.
The equals Method obj is the object to be tested for equality. The method returns true if obj and the invoking object are both Comparator objects and use the same ordering. Otherwise, it returns false. Overriding equals( ) is unnecessary, and most simple comparators will not do so.
The == operator can't compare conflicting objects, so at that time the compiler surrenders the compile-time error. The equals() method can compare conflicting objects utilizing the equals() method and returns “false”.
Indicates whether some other object is "equal to" this comparator. This method must obey the general contract of Object. equals(Object) . Additionally, this method can return true only if the specified object is also a comparator and it imposes the same ordering as this comparator.
In java both == and equals() method is used to check the equality of two variables or objects. == is a relational operator which checks if the values of two operands are equal or not, if yes then condition becomes true. equals() is a method available in Object class and is used to compare objects for equality.
Guava has the Equivalence
class, which does pretty much what you are asking for.
You can even wrap an Object in an Equivalence
to decorate an Object with a better hashCode() equals() implementation (e.g. if you want to use an Object with a bad equals() hashCode() as a Map key but don't have access to the sources)
Here's an example: arrays don't have proper implementations of equals() and hashCode(), but here's an Equivalence for char arrays:
private static final Equivalence<char[]> CHAR_ARRAY_EQUIV = new Equivalence<char[]>(){
@Override
protected boolean doEquivalent(char[] a, char[] b) {
return Arrays.equals(a, b);
}
@Override
protected int doHash(char[] chars) {
return Arrays.hashCode(chars);
}
};
Sample code:
final char[] first ={'a','b'};
final char[] second ={'a','b'};
Assert.assertFalse(first.equals(second));
Assert.assertFalse(first.hashCode() == second.hashCode());
final Wrapper<char[]> firstWrapped = CHAR_ARRAY_EQUIV.wrap(first);
final Wrapper<char[]> secondWrapped = CHAR_ARRAY_EQUIV.wrap(second);
Assert.assertTrue(firstWrapped.equals(secondWrapped));
Assert.assertTrue(firstWrapped.hashCode() == secondWrapped.hashCode());
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