java1.7集合源码赏析系列:HashMap

HashMap基于哈希表的 Map 接口的实现。此实现提供所有可选的映射操作,并允许使用 null 值和 null 键。继承于java.util.AbstractMap

//数据存储
  transient Entry<K,V>[] table = (Entry<K,V>[]) EMPTY_TABLE;

可以看到hashmap的数据是存在一个数组里面,这个数组放的是Entry对象 Entry部分代码:

final K key;
        V value;
        Entry<K,V> next;
        int hash;

Entry是一个单项链表。 我们再看一下hashmap 放入一个数据的时候做了什么

public V put(K key, V value) {
 //map是空时初始化table
        if (table == EMPTY_TABLE) {
            inflateTable(threshold);
        }
        //key是null时将数据放入table[0]下的链表中
        if (key == null)
            return putForNullKey(value);
        //计算key的hash值,找到这个key对应的链表
        int hash = hash(key);
        int i = indexFor(hash, table.length);
        //遍历链表,为什么会有e!=null的判断,答案留在最后揭晓
        for (Entry<K,V> e = table[i]; e != null; e = e.next) {
            Object k;
            //判断key是否存在,如果存在更新value
            if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
                V oldValue = e.value;
                e.value = value;
                e.recordAccess(this);
                return oldValue;
            }
        }
    //总数自增
        modCount++;
        //没有找到entry,则会创建一个entry实例
        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;
            //获取这个key所在的链表地址
            bucketIndex = indexFor(hash, table.length);
        }
    //创建一个新的entry
        createEntry(hash, key, value, bucketIndex);
    }

void createEntry(int hash, K key, V value, int bucketIndex) {
        Entry<K,V> e = table[bucketIndex];
        //创建一个新的entry实例,将它置于链表数组,如果有hash冲突的话,它会位于原链表头,如果没有hash冲突,这个新实例的next就是Null
        table[bucketIndex] = new Entry<>(hash, key, value, e);
        size++;
    }

总结

1.hashmap put值后 如果是新增,会返回null,如果是更新,会返回更新后的value 2.hashmap存在线程安全的问题 3.hashmap会把有hash冲突的键值对放在链表头,个人的理解是为了代码的简洁,否则的话需要在更新的时候多一层判断

经验分享 程序员 微信小程序 职场和发展