在HashMap中,通过对元素的hashCode进行一次hash运算得到一个hash值,然后再结合HashMap的size计算出元素插入table[]中的位置,为了避免哈希冲突,JDK在各个版本中都对hash算法算法进行了不断的优化,下面是JDK5至JDK8的演化过程。

JDK5

  1. static final int hash(Object key) {
  2. int h;
  3. return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
  4. }

JDK6

  1. static int hash(int h) {
  2. // This function ensures that hashCodes that differ only by
  3. // constant multiples at each bit position have a bounded
  4. // number of collisions (approximately 8 at default load factor).
  5. h ^= (h >>> 20) ^ (h >>> 12);
  6. return h ^ (h >>> 7) ^ (h >>> 4);
  7. }

JDK7

  1. final int hash(Object k) {
  2. int h = hashSeed;
  3. if (0 != h && k instanceof String) {
  4. return sun.misc.Hashing.stringHash32((String) k);
  5. }
  6. h ^= k.hashCode();
  7. // This function ensures that hashCodes that differ only by
  8. // constant multiples at each bit position have a bounded
  9. // number of collisions (approximately 8 at default load factor).
  10. h ^= (h >>> 20) ^ (h >>> 12);
  11. return h ^ (h >>> 7) ^ (h >>> 4);
  12. }

JDK8

  1. static final int hash(Object var0) {
  2. int var1;
  3. return var0 == null ? 0 : (var1 = var0.hashCode()) ^ var1 >>> 16;
  4. }