Search |
||
Hashmap ImplementationPosted by tchangu on June 18, 2005 at 10:40 AM PDT
Always thought that the Hash implementations (table & map) used buckets that are prime in number. But recently, after digging around the source code to see what that default size resulted in a bit of a puzzling situation... So let me start with a bit of rambling of my understanding about hashtables. They are created by using a hashing function to hash the keys into buckets along with associated value. It is possible that different keys might hash into the same bucket causing Hash collision. So the goal of hash table design is to spread out the key pairs across the table. When the hash value (from hashCode) is converted into a valid array index by performing a modulus operation against the size of the hashtable, having the hashtable size as a prime number results in uniform spread of indexes. Of course java.util.Hashtable doesn't deviate from this and can be seen in the following code snippet int hash = key.hashCode(); The new Hashmap implementation, however, takes a different approach and, unfortunately, it took a long time for me to even look at it. The new implementation breaks the conventional thinking of needing a prime number for initializing the number of hash buckets. It now requires that size of the hash table be power of two!!! Accordingly, the constructor for the hashmap is public HashMap() { Now scope this out. The get method public V get(Object key) { performs an extra hash call and the comment in the code specifies The shift distances in this function were chosen as the result and the code snippet is like this h += ~(h << 9); "...The best answer is to read Donald Knuth's Art of Computer So I am now waiting to check this book out see why power of two works? However I am not sure if I will be able to get an answer for those numbers! Your thoughts??? »
Related Topics >>
J2SE Comments
Comments are listed in date ascending order (oldest first)
|
||
|
|