I would like to know the complete functionality how hashing is done in a hashmap? not theoritically . In practical with example.
Asked
Active
Viewed 181 times
0
-
2Have you tried using *google*? – TheLostMind Apr 13 '15 at 06:12
-
1Did you tried Google? You would see loads of articles about the same. – SMA Apr 13 '15 at 06:12
-
1Have a look into the code of the class. Extract the `$JAVA_HOME/src.zip`, which is part of your JDK installation. – SubOptimal Apr 13 '15 at 06:23
-
Go through the HashMap source code. – Touchstone Apr 13 '15 at 06:25
-
Read this http://stackoverflow.com/questions/6493605/how-does-a-hashmap-work-in-java – Mateusz Sroka Apr 13 '15 at 06:36
-
already answerd here http://stackoverflow.com/questions/17196159/how-does-hashing-in-java-works – Premraj Apr 13 '15 at 06:38
1 Answers
0
Take a look at below code, it gives an idea of behind the scenes when we insert a pair into map.
public V put(K key, V value) {
if (key == null)
return putForNullKey(value);
int hash = hash(key.hashCode());
int i = indexFor(hash, table.length);
for (Entry<K,V> e = table[i]; e != null; e = e.next) {
Object k;
if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
V oldValue = e.value;
e.value = value;
e.recordAccess(this);
return oldValue;
}
}
modCount++;
addEntry(hash, key, value, i);
return null;
}
Now the below code shows how hashcode is computed for a string. Similarly other datatypes have their own implementations, you can check that in grepcode. If you have a custom class then hash code needs to implemented by you specifically or it will be taken from the default object class.
/**
* Returns a hash code for this string. The hash code for a
* <code>String</code> object is computed as
* <blockquote><pre>
* s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
* </pre></blockquote>
* using <code>int</code> arithmetic, where <code>s[i]</code> is the
* <i>i</i>th character of the string, <code>n</code> is the length of
* the string, and <code>^</code> indicates exponentiation.
* (The hash value of the empty string is zero.)
*
* @return a hash code value for this object.
*/
public int hashCode() {
int h = hash;
if (h == 0) {
int off = offset;
char val[] = value;
int len = count;
for (int i = 0; i < len; i++) {
h = 31*h + val[off++];
}
hash = h;
}
return h;
}
Hope it explains !!!
Look @ grepcode for more details. Also visit this stackoverflow page.