General Contracts for hashCode() in Java
1) If two objects are equal by equals() method then there hashcode returned by hashCode() method must be same.
2) Whenever hashCode() mehtod is invoked on the same object more than once within single execution of application, hashCode() must return same integer provided no information or fields used in equals and hashcode is modified. This integer is not required to be same during multiple execution of application though.
3) If two objects are not equals by equals() method it is not require that there hashcode must be different. Though it’s always good practice to return different hashCode for unequal object. Different hashCode for distinct object can improve performance of hashmap or hashtable by reducing collision.
To better understand concept of equals and hashcode and what happens if you don’t override them properly I would recommend understanding of How HashMap works in Java
Overriding hashCode method in Java
1) Take a prime hash e.g. 5, 7, 17 or 31 (prime number as hash, results in distinct hashcode for distinct object)
2) Take another prime as multiplier different than hash is good.
3) Compute hashcode for each member and add them into final hash. Repeat this for all members which participated in equals.
4) Return hash
Some facts about hashcode with HASHSET
- There's no need to call equals if
hashCodediffers - There's no need to call
hashCodeif(obj1 == obj2) - There's no need for
hashCodeand/or equals just to iterate - you're not comparing objects - When needed to distinguish in between objects.
A set is a collection of unique objects, with Java defining uniqueness in that it doesn't equal anything else (equals returns false).
The HashSet takes advantage of hashcodes to speed things up. It assumes that two objects that equal eachother will have the same hash code. However it does not assume that two objects with the same hash code mean they are equal. This is why when it detects a colliding hash code, it only compares with other objects (in your case one) in the set with the same hash code.
No comments:
Post a Comment