I know that hashmap actually uses hashcode to store and retrive object from hashtable but my doupt is which hashcode it uses. map actually contains hashcode for key and hashcode for its value. let's consider this way
Map<String,String> student=new HashMap();
student.put("name", "foo");
System.out.println("name".hashCode());
System.out.println("foo".hashCode());
In here hashcode for name(key) is 3373707 hashcode for foo(value) is 101574
my doupt is which one it should use to store and retrive object
As you can see from the following code in HashMap
, it uses its own hash function:
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
It uses the object's hashCode
, but xor
s it and arithmetically shifts it to the right 16 times.
To answer your question specifically, it uses the hashCode
of the key and not the value.