- Reflexive: Object must equal to itself.
- Symmetric: if a.equals(b) is true and then b.equals(a) must be true.
- Transitive: if a.equals(b) is true and then b.equals(c) is be true, then c.equals(a) must be true.
- Consistent: multiple invocations of a.equals(b) consistently return true or false, provided no information used in equals comparisons on the objects are modified.
- Null comparison: if a.equals(null) should return false.
Step to override equals method
- Return true if they are having same address
- Return false if the reference object is null
- Check subclass or same class by instanceof method
- Type cast the object
- Compare individual attributes and should avoid NullPointerException
Notice also how verbose Java is, even in an operation as basic as comparing Money for equality. I preferably use the JDK7’s Objects and Guava’s Objects as below:
The new edition of the code will become easier.
Equals and hashCode contract in Java
When using a hash-based Collection or Map such as HashSet, LinkedHashSet, HashMap, HashTable, or WeakHashMap…, the hashCode() of key objects that you put into Collection never changes while the object is in the collection.For equals and hashCode contract, there are two ideas:
- If two objects are equal by equals() then their hashCode must be same.
- If two objects are having the same hashCode then it does not mean that both objets are equal by equals() method. They might be un-equal also, so their hashCode might be the same or different.
No comments:
Post a Comment