快速提问,确保我很清楚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的工作原理如下:
获得它:
我是否正确理解了这个概念?
非常感谢!
修改
非常感谢,所以要完成: - How does Java HashMap store entries internally - How does a Java HashMap handle different objects with the same hash code?和
答案 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重新创建一个哈希来“强化”它。
我希望有帮助