Hashmap以及它如何在场景后面工作

时间:2013-10-28 20:35:52

标签: java linked-list hashmap

快速提问,确保我很清楚java中的HashMap是如何工作的。

以下是代码示例:

//String key = new String("key");
//String val = new String("value");
String key = "key";
String val = "value";

HashMap map = new HashMap();
map.put(key, val);

System.out.println("hashmap object created. Its key hashcode = "+key.hashCode());
// the hashcode is 106079
System.out.println("hashmap object value for key = "+map.get(key));

// Let's store using a key with same hashcode
Integer intkey = new Integer(106079);
val = "value2";
map.put(intkey, val);
System.out.println("hashmap object created. Its intkey hashcode = "+intkey.hashCode());
// this returns 106079 once again. So both key and intkey have the same hashcode

// Let's get the values
System.out.println("hashmap object value for intkey = "+map.get(intkey));
System.out.println("hashmap object value for key = "+map.get(key));

返回的值与预期一致。我在场景后面看到,HashMap的工作原理如下:

  1. 获取密钥/值。
  2. 从密钥中创建哈希码。
  3. 在桶中存储密钥和值对象(在我的案例中为桶号106079)
  4. 第二个也是如此。

    1. 将它存储在同一个存储桶中,但由于这是一个LinkedList,我想将它存储在“下一个可用的分配”中。
    2. 获得它:

      1. 拿起密钥,获取哈希码,
      2. 看看水桶,
      3. 然后查看LinkedList中第一个元素的键
      4. 然后检查密钥是否通过,元素是否匹配,如果没有,则继续下一个,依此类推,直到可以检索到值。
      5. 我是否正确理解了这个概念?

        非常感谢!

        修改

        非常感谢,所以要完成:   - How does Java HashMap store entries internally   - How does a Java HashMap handle different objects with the same hash code?

        • 不应该有那么多“桶”
        • 一个桶与一个条目不同。存储桶是共享相同存储桶#的所有条目的逻辑集合(在Java情况下,它是密钥的hashCode()的函数)。如其他答案中所述,存储桶溢出可以通过多种方式实现,不一定在列表中。
        • 还有其他现有的碰撞解决方案:http://en.wikipedia.org/wiki/Hash_table#Collision_resolution
        • 它使用Object的equals方法来比较和检索同一个桶中的对象。

3 个答案:

答案 0 :(得分:3)

请注意,HashMap可以通过多种方式实现哈希码collision resolution,而不仅仅是使用您提到的链接列表

Java的HashMap实现不仅使用LinkedList策略来处理具有相同key.hashCode()值的键值。

另外,您可能需要阅读this文章

答案 1 :(得分:1)

是的,您的理解是正确的。请注意,为一个桶分配了许多哈希码:在一个新的HashMap中,共有16个桶,每个桶总共分配2个 32 / 16 = 2 28 哈希码。

答案 2 :(得分:0)

您的理解是可以的,但考虑到有几种实现。 HashMap用于存储值的实际哈希码可能不是106079.这是一个实现(java-6-openjdk):

public V put(K key, V value) {
    if (key == null)
        return putForNullKey(value);
    int hash = hash(key.hashCode());
    int i = indexFor(hash, table.length);
    for (Entry<K,V> e = table[i]; e != null; e = e.next) {
        Object k;
        if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
            V oldValue = e.value;
            e.value = value;
            e.recordAccess(this);
            return oldValue;
        }
    }

    modCount++;
    addEntry(hash, key, value, i);
    return null;
}

请注意hash方法,该方法包含以下内容:

/**
 * 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);
}

所以在这个JVM的例子中,它不使用106079作为哈希,因为HashMap重新创建一个哈希来“强化”它。

我希望有帮助

相关问题