[英]put method of Hashmap
我看到在HashMap类的put方法的实现中,表存储区是使用int i = indexFor(hash, table.length);
然后它将一个条目添加到该存储桶-如果哈希码和密钥不相等,则为“ i”。 如果它们相等,则替换旧值。
源代码:
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++;
}
indexOf()方法的返回值永远不会超过数组的大小。 检查HashTable的实现,它与HashMap的实现不完全相同,但是您将获得有关基本哈希的想法。
假设您有4个MyClass对象。 其哈希码值分别为11,12,13,14。 并且您的默认哈希图大小为10,则索引将如下所示-
index = hashcode % table.length;
1 = 11 % 10 ;
2 = 12 % 10 ;
3 = 13 % 10 ;
1,2,3是索引值,您的条目将存储在数组中。
如果您的类哈希码为21,则其索引将为21%10 = 1;
索引1已经有一个Entry对象,因此它将存储为LinkedList。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.