【发布时间】:2014-08-04 07:12:58
【问题描述】:
我看到在 HashMap 类的 put 方法的实现中,表桶是使用int i = indexFor(hash, table.length); 获得的,然后它向该桶添加一个条目 - 如果哈希码和键不相等,则为“i”。如果它们相等,则替换旧值。
- 它如何使用密钥找到正确的存储桶?如果存储桶不存在怎么办?
- 它如何评估是否需要将其添加到同一个桶或不同的桶中?
- 当哈希码相同而键不同时会发生什么?如果哈希码相同,那么条目应该在同一个桶中,但我在 put 方法的代码中没有看到!
源代码:
public V put(K key, V value) {
if (table == EMPTY_TABLE) {
inflateTable(threshold);
}
if (key == null)
return putForNullKey(value);
int hash = hash(key);
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;
}
void addEntry(int hash, K key, V value, int bucketIndex) {
if ((size >= threshold) && (null != table[bucketIndex])) {
resize(2 * table.length);
hash = (null != key) ? hash(key) : 0;
bucketIndex = indexFor(hash, table.length);
}
createEntry(hash, key, value, bucketIndex);
}
void createEntry(int hash, K key, V value, int bucketIndex) {
Entry<K,V> e = table[bucketIndex];
table[bucketIndex] = new Entry<>(hash, key, value, e);
size++;
}
【问题讨论】:
-
这里的问题太多了,一个问题。此外,通过阅读散列集合的一般工作原理可以很容易地回答这些问题。
-
我在这篇文章中看到至少 4 个问题...
-
要获得所有问题的答案,我认为最好查看`HashMap的源代码,
-
例如,我使用了Google,然后我到达了,this article 回答了您的许多问题。 Google 是您的朋友。
标签: java collections hashmap