hashMap的数据结构:一个数组,数组的每个元素是一个链表的头
链表的每个元素的哈希值是一样的
//map:添加一对key_value
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);//根据哈希值获取对应的table的位置
for (Entry<K,V> e = table[i]; e != null; e = e.next) {//初始值为该table的头
Object k;
if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {//判断哈希值是否相等,判断key是否相等,如果相等,则修改值
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);//将链表的头放到新节点的next中,将新头放到table数组中
size++;
}
本文深入解析了HashMap的数据结构实现原理,介绍了其通过数组加链表的方式存储数据,并详细阐述了put方法的工作流程,包括如何计算哈希值、查找键值对、处理冲突以及扩容机制。
438

被折叠的 条评论
为什么被折叠?



