I understand there is a hashing technique is applied to a key to store its value in the memory address.
But I don't understand how the collision is happening here? Which hashing algorithm does Java use to create a memory space? Is it MD5?
4 Answers 4
The basic idea of HashMap
is this:
- A
HashMap
is really an array of special objects that hold both Key and Value. - The array has some amount of buckets (slots), say 16.
- The hashing algorithm is provided by the
hashCode()
method that every object has. Therefore, when you are writing a newClass
, you should take care of properhashCode()
andequals()
methods implementation. The default one (of theObject
class) takes the memory pointer as a number. But that's not good for most of the classes we would like to use. For example, theString
class uses an algorithm that makes the hash from all the characters in the string - think of it like this:hashCode = 1.char + 2.char + 3.char...
(simplified). Therefore, two equal Strings, even though they are on a different location in the memory, have the samehashCode()
. - The result of
hashCode()
, say "132", is then the number of bucket where the object should be stored if we had an array that big. But we don't, ours is only 16 buckets long. So we use the obvious calculation'hashcode % array.length = bucket'
or'132 mod 16 = 4'
and store the Key-Value pair in a bucket number 4. - If there's no other pair yet, it's ok.
- If there's one with Key equal to the Key we have, we remove the old one.
- If there's another Key-Value pair (collision), we chain the new one after the old one into a linked list.
- If the backing array becomes too full, so we would have to make too many linked lists, we make a new array with doubled length, rehash all the elements and add them into the new array, then we dispose the old one. This is most likely the most expensive operation on
HashMap
, so you want to tell yourMaps
how many buckets you'll use if you know it in before. - If somebody tries to get a value, he provides a key, we hash it, mod it, and then go through the potential linked list for the exact match.
An image, courtesy of Wikipedia: The graphics
In this case,
- there is an array with 256 buckets (numbered, of course, 0-255)
- there are five people. Their hashcodes, after being put through
mod 256
, point to four different slots in the array. - you can see Sandra Dee didn't have a free slot, so she has been chained after John Smith.
Now, if you tried to look up a telephone number of Sandra Dee, you would hash her name, mod it by 256, and look into the bucket 152. There you'd find John Smith. That's no Sandra, look further ... aha, there's Sandra chained after John.
-
If you find any link that explain with images please put it here.. That will be very helpful ..Sahal– Sahal06/05/2012 09:55:40Commented Jun 5, 2012 at 9:55
-
1Done. It's from this article in wikipedia.Petr Janeček– Petr Janeček06/05/2012 10:17:43Commented Jun 5, 2012 at 10:17
-
1And now, when you know this, the this is the
String
's realhashCode()
implementation. And some random links on the prime number selection inhashCode()
.Petr Janeček– Petr Janeček06/05/2012 10:38:01Commented Jun 5, 2012 at 10:38 -
Unfortunately this isn't what
HashMap
actually does. It XORs the high and low 16 bits of thehashCode()
together, for a start. It isn't whatHashTable
does either.user207421– user20742103/28/2018 04:19:37Commented Mar 28, 2018 at 4:19 -
2@EJP Right. And it xors with 2<sup>n</sup>-1 instead of using a mod, so keys whose hashes differ only in the high bits would always collide without this, eh, technique. And it can treeify the colliding keys in a single bucket when the linked list for overflow entries gets too long. There's probably a dozen additional implementation details that are helping making
HashMap
really fast in practice. But obviously this answer does not contain them not to confuse the OP. He was a novice at the time, and needed to know the algorithmic basics, not the low-level optimizations, I believe.Petr Janeček– Petr Janeček03/28/2018 07:32:19Commented Mar 28, 2018 at 7:32
Here Hash
does not mean for Hashing
techniques such as MD5. Its the HashCode of memory location used to store an Object
for a particular key.
Readings:
This is somewhat more clearer explanation of How HashMap works?
-
For example if you have 100 records in the HashTable, and you want to find out a key with 'Men In Black', How fast it finds the value of it? I think it will not take more than one iteration to find it Q(1). What I felt is compiler create a hashcode of 'Men In Black' and it store the value in that particular memory location. Later when we try to retrieve this, it uses the hascode to find the value of it.....Am i missing something ?.... If that is not the case how run time of the key search is one ie.Q(1) ?Sahal– Sahal06/05/2012 09:25:49Commented Jun 5, 2012 at 9:25
-
2The Key in Map is stored under given position of array (memory). The position is set by RunTime (not compiler), using algorithm that use transformed hashCode of object and array length. Time needed to retrieve element is O(1), that do not require any iteration.Damian Leszczyński - Vash– Damian Leszczyński - Vash06/05/2012 09:32:41Commented Jun 5, 2012 at 9:32
-
It is not the '
hashCode
of a memory location'. ThehashCode
yields the memory location, by a process involving further computation. Remainder of the answer consists merely of links.user207421– user20742103/28/2018 04:21:03Commented Mar 28, 2018 at 4:21
As default implementation hashCode()
function in Object
class return the memory address as the hash which is used as key in HashTable
& HashMap
.
-
For example if you have 100 records in the HashTable, and you want to find out a key with 'Men In Black', How fast it finds the value of it? I think it will not take more than one iteration to find it Q(1). What I felt is compiler create a hashcode of 'Men In Black' and it store the value in that particular memory location. Later when we try to retrieve this, it uses the hascode to find the value of it.....Am i missing something ?.... If that is not the case how run time of the key search is one ie.Q(1) ?Sahal– Sahal06/05/2012 09:24:21Commented Jun 5, 2012 at 9:24
-
1It will look at the memory location where String object with value 'Men In Black' is stored. This memory location becomes the hashcode which is used to retrieve the value. Ideally it should be Q(1) , generally due to collision and for optimizing the memory used, there will be slight variation and for all practical purposes it can be taken as Q(1). The variation will depend on the number of items in bucket at index calculated from hashcode. Its not necessary that all 100 items in hashmap will have unique index.ejb_guy– ejb_guy06/05/2012 09:42:11Commented Jun 5, 2012 at 9:42
-
Also, the
String
class has it's ownhashCode()
implementation, it doesn't take the memory location as it, but uses an algorithm to make a hash from the actual characters in the String...Petr Janeček– Petr Janeček06/05/2012 09:47:29Commented Jun 5, 2012 at 9:47 -
Yaah, here I confused was, For strings it create hash from its own key... But for integer keys ?Sahal– Sahal06/05/2012 10:25:05Commented Jun 5, 2012 at 10:25
-
@Sahal I think you know this by today, but every object has its own hashCode method, even Integer (where the hashCode == value).Petr Janeček– Petr Janeček03/28/2018 07:20:13Commented Mar 28, 2018 at 7:20
After going through @Slanec's answer, do see the javadoc from Java-8, as there are significant changes. For ex: 'TREEIFY' where the LinkedList is converted to a TreeMap in case the threshold number of entries per bucket (currently 8) is reached.
-
The question is about
HashMap
andHashTable
, not aboutTreeMap
, which doesn't use hashing at all.user207421– user20742103/28/2018 04:23:28Commented Mar 28, 2018 at 4:23 -
@EJP What the author here meant was that if a large number of collisions happen to a single bin, at one point instead of a singly linked list the colliding keys get restructured into a tree, not unsimilar to a
TreeMap
(with both obvious and unobvious differences, e.g. noncomparable keys are sorted on theirhashCode()
). This helps to protect against catastrophic cases of many collisions where a pre-Java-8HashMap
slowly degrades to a linked list.Petr Janeček– Petr Janeček03/28/2018 07:19:06Commented Mar 28, 2018 at 7:19