作者:我爱盘小静永远永远 | 来源:互联网 | 2022-12-22 14:43
This question already has an answer here:
这个问题在这里已有答案:
- Do keys with different hashes also get mapped to the same index in HashMap? 3 answers
- 具有不同哈希值的键是否也映射到HashMap中的相同索引? 3个答案
This is the code of HashMap.java (docjar). Hash for key is calculated on line 431. This helps to fetch the index i on line 432. This all the entries at that index should have the same hash. Why is the check for hash equality made again on line 440 ? (if (e.hash == hash )
这是HashMap.java(docjar)的代码。密钥的哈希值在第431行计算。这有助于在第432行获取索引i。该索引处的所有条目应具有相同的哈希值。为什么在第440行再次检查哈希等式? (if(e.hash == hash)
private void putForCreate(K key, V value) {
430 int hash = (key == null) ? 0 : hash(key.hashCode());
431 int i = indexFor(hash, table.length);
432
433 /**
434 * Look for preexisting entry for key. This will never happen for
435 * clone or deserialize. It will only happen for construction if the
436 * input Map is a sorted map whose ordering is inconsistent w/ equals.
437 */
438 for (Entry e = table[i]; e != null; e = e.next) {
439 Object k;
440 if (e.hash == hash &&
441 ((k = e.key) == key || (key != null && key.equals(k)))) {
442 e.value = value;
443 return;
444 }
445 }
446
447 createEntry(hash, key, value, i);
448 }
1 个解决方案