HashMap的Hash算法

2018-10-19  本文已影响0人  响响月月

HashMap定位

  1. 取key的HashCode值
  2. 高位运算
  3. 计算索引

求HashCode值

  1. Integer: value
public static int hashCode(int value) {
      return value;
}
  1. Long: 于高位做异或
public static int hashCode(long value) {
      return (int)(value ^ (value >>> 32));
}
  1. Double: 变成long型,按long取HashCode
public static int hashCode(double value) {
     long bits = doubleToLongBits(value);
     return (int)(bits ^ (bits >>> 32));
}
  1. String: h = 31 * h + val[i];
public int hashCode() {
      int h = hash;
      if (h == 0 && value.length > 0) {
          char val[] = value;
          for (int i = 0; i < value.length; i++) {
              h = 31 * h + val[i];
          }
          hash = h;
      }
      return h;
}

高位运算

高16位异或低16位

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

计算索引

扩容

超过capacity * 0.75扩容
扩为2 * capacity

上一篇 下一篇

猜你喜欢

热点阅读