Why is there a hashcode conversion to get a hash, and is this a good idea for all keys?

I see that the hashmap implementation applies some kind of conversion to hashCode to get the actual hash.
Can someone please help me understand how this conversion works, and additionally, if it matters, if the storage object is an integer?

0
source share
1 answer

As taken from the Javadoc of the hash(Object) method in the OpenJDK implementation of Java 8 HashMap (assuming it's a JVM, you're worried):

  / **
  * Computes key.hashCode () and spreads (XORs) higher bits of hash
  * to lower.  Because the table uses power-of-two masking, sets of
  * hashes that vary only in bits above the current mask will
  * always collide.  (Among known examples are sets of Float keys
  * holding consecutive whole numbers in small tables.) So we
  * apply a transform that spreads the impact of higher bits
  * downward.  There is a tradeoff between speed, utility, and
  * quality of bit-spreading.  Because many common sets of hashes
  * are already reasonably distributed (so don't benefit from
  * spreading), and because we use trees to handle large sets of
  * collisions in bins, we just XOR some shifted bits in the
  * cheapest possible way to reduce systematic lossage, as well as
  * to incorporate impact of the highest bits that would otherwise
  * never be used in index calculations because of table bounds.
  * /
 static final int hash (Object key) {
     int h;
     return (key == null)?  0: (h = key.hashCode ()) ^ (h >>> 16);
 } 
+2
source

Source: https://habr.com/ru/post/1246883/


All Articles