Basic Facts about HashMap.
1. HashMap will generate hashcode for each key irrespective of the object type.
2. To be specific - hashcode will be generated based on the key and value(i.e. entry)
Experiment:
Consider a user-defined object(eg. SPObject) is the key for a hashmap; SPObject has only one parameter (name) in it. Refer: http://www.programcreek.com/2011/07/java-equals-and-hashcode-contract/
If hashCode() and equals() are not written properly in the SPObject class, the issues are below.
Put 2 entries - new SPObject("SP") & new SPObject("SP"). These are treated as different object and gets stored in Map successfully.
map.get(new SPObject("SP")) will return null.
map.contains(new SPObject("SP")) will return false.
This is the result, if the hashCode/equals contract is not handled properly.
hashCode() | equals() | Treated as | Description
No | No | Duplicate | Stored in different buckets.
| Treated as different object.
Yes | No | Duplicate | Stored in same bucket.
| Treated as different object.
| Because, the default(Object) equals method will check only the reference of objects.
No | Yes | Duplicate | Stored in different buckets.Treated as different object
Yes(hashlogic) | Yes | Unique | Stored in same bucket.Treated as same object.Efficient.
Yes(constant) | Yes | Unique | Stored in same bucket.Treated as same object.
| Inefficient, because it will iterate bucket elements for equality check.