I have been trying to understand the internal implementation of java.util.HashMap and java.util.HashSet.
Following are the doubts popping in my mind for a while:
- Whats is the importance of the
@Override public int hashcode()in a HashMap/HashSet? Where is this hash code used internally? - I have generally seen the key of the HashMap be a
StringlikemyMap<String,Object>. Can I map the values againstsomeObject(instead of String) likemyMap<someObject, Object>? What all contracts do I need to obey for this happen successfully?
Thanks in advance !
EDIT:
- Are we saying that the hash code of the key (check!) is the actual thing against which the value is mapped in the hash table? And when we do
myMap.get(someKey);java is internally callingsomeKey.hashCode()to get the number in the Hash table to be looked for the resulting value?
Answer: Yes.
EDIT 2:
- In a
java.util.HashSet, from where is the key generated for the Hash table? Is it from the object that we are adding eg.mySet.add(myObject);thenmyObject.hashCode()is going to decide where this is placed in the hash table? (as we don't give keys in a HashSet).
Answer: The object added becomes the key. The value is dummy!