Actually, this is a good idea!
But make sure you use this method to determine inequality, not equality. Hashing code can be faster than checking for equality, especially when saving the hash code (for example, in java.lang.String ).
If two objects have different hash codes, they must be different, otherwise they can be the same. For example, you can use this method as follows
Object a, b; if(a.hashCode() == b.hashCode()){ if(a.equals(b)) return true; } return false;
Remember that in some cases, the code above may be slower than using only equals() , especially if in most cases a makes equal to b .
From the documentation of Object.java :
- If two objects are equal in accordance with the
equals(Object) method, then calling the hashCode method for each of the two objects should produce the same integer result. - It is not required that the two objects be unequal in the
equals(java.lang.Object) method equals(java.lang.Object) , then a call to the hashCode method for each of the two objects should produce separate integer results. However, the programmer should be aware that creating separate integer results for unequal objects can improve the performance of hash tables.
source share