java HashMap 实现原理探究

欢迎进入Java社区论坛,与200万技术人员互动交流 >>进入

  modCount++;

  addEntry(hash, key, value, i);

  return null;

  }

  我们看到先对key重新计算哈希值,然后根据该值找到数组小标,如果数组的这个位置有值,那么在这个位置上就以链表形式存储,新的值放在链表头。

  /**

  * Applies a supplemental hash function to a given hashCode, which

  * defends against poor quality hash functions. This is critical

  * because HashMap uses power-of-two length hash tables, that

  * otherwise encounter collisions for hashCodes that do not differ

  * in lower bits. Note: Null keys always map to hash 0, thus index 0.

  */

  static int hash(int h) {

  // This function ensures that hashCodes that differ only by

  // constant multiples at each bit position have a bounded

  // number of collisions (approximately 8 at default load factor)。

  h ^= (h >>> 20) ^ (h >>> 12);

  return h ^ (h >>> 7) ^ (h >>> 4);

  }

  3、get 取方法

  public V get(Object key) {

  if (key == null)

  return getForNullKey();

  int hash = hash(key.hashCode());

  for (Entry<K,V> e = table[indexFor(hash, table.length)];

  e != null;

  e = e.next) {

  Object k;

  if (e.hash == hash && ((k = e.key) == key || key.equals(k)))

  return e.value;

  }

  return null;

  }

  先计算key的哈希值,然后找到数组中对应位置,让后通过for循环来遍历该位置上的链表,并用equals比较查找。

[1][2]

谁的指间滑过了千年时光;谁在反反复复中追问可曾遗忘;

java HashMap 实现原理探究

相关文章:

你感兴趣的文章:

标签云: