java 源码解析 hashMap

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++;     }

    原文作者:current_bp
    原文地址: https://blog.csdn.net/current112233/article/details/78202898
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞