HashMap jdk1.8基础和源码分析

243 阅读8分钟

HashMap是基于哈希表的Map实现

哈希表的特点:关键字 key 和它在表中的存放位置 bucketIndex 之间存在一种确定的关系。即bucketIndex = hash(key)

哈希函数:一般情况下,需要在关键字与它在表中的存储位置之间建立一个函数关系,以f(key)作为关键字为key的记录在表中的位置,通常称这个函数f(key)为哈希函数。

hash : 翻译为“散列”,就是把任意长度的输入,通过散列算法,变成固定长度的输出,该输出就是散列值。这种转换是一种压缩映射,散列值的空间通常远小于输入的空间,不同的输入可能会散列成相同的输出,所以不可能从散列值来唯一的确定输入值。

hash冲突:关键字 key 和它在表中的存放位置 bucketIndex之间存在一种确定的关系。多个key计算出来的bucketIndex是一样的,即产生哈希冲突,需要存放在一个位置。

源码分析:

JDK 1.7及以前版本链表是头插法,JDK1.8链表是尾插法

JDK 1.7的分析:www.cnblogs.com/chengxiao/p…

以下是JDK1.8的源码分析:

构造函数HashMap()

只是指定了加载因子loadFactor 或者初始容量,并没有进行new的操作。

//设置初始容量和加载因子(加载因子默认为0.75)
public HashMap(int initialCapacity, float loadFactor) {
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal initial capacity: " +
                                               initialCapacity);
        if (initialCapacity > MAXIMUM_CAPACITY)
            initialCapacity = MAXIMUM_CAPACITY;
        if (loadFactor <= 0 || Float.isNaN(loadFactor))
            throw new IllegalArgumentException("Illegal load factor: " +
                                               loadFactor);
        this.loadFactor = loadFactor;
        this.threshold = tableSizeFor(initialCapacity);
    }

   //设置初始容量,回调 HashMap(int initialCapacity, float loadFactor)
    public HashMap(int initialCapacity) {
        this(initialCapacity, DEFAULT_LOAD_FACTOR);
    }

  //默认加载因子为0.75
    public HashMap() {
        this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
    }

   
    public HashMap(Map<? extends K, ? extends V> m) {
        this.loadFactor = DEFAULT_LOAD_FACTOR;
        putMapEntries(m, false);
    }

   //是否需要扩容,赋值
    final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) {
        int s = m.size();
        if (s > 0) {
            if (table == null) { // pre-size
                float ft = ((float)s / loadFactor) + 1.0F;
                int t = ((ft < (float)MAXIMUM_CAPACITY) ?
                         (int)ft : MAXIMUM_CAPACITY);
                if (t > threshold)
                    threshold = tableSizeFor(t);
            }
            else if (s > threshold)
                resize();
            for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) {
                K key = e.getKey();
                V value = e.getValue();
                putVal(hash(key), key, value, false, evict);
            }
        }
    }

get(key) 取操作

如果没有找到匹配key的value,返回null;否则返回value

tab[(n - 1) & hash] 相当于hash % (n - 1), n是2的整数幂,例如:8(2的三次幂) -> 0111。注释里简写为table[hash]

   public V get(Object key) {
        Node<K,V> e;
        return (e = getNode(hash(key), key)) == null ? null : e.value;
    }

    //   
    final Node<K,V> getNode(int hash, Object key) {
        Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
        if ((tab = table) != null && (n = tab.length) > 0 &&
            (first = tab[(n - 1) & hash]) != null) {     //如果table不为空,且table[hash]不为空,否则返回null
            if (first.hash == hash && // always check first node
                ((k = first.key) == key || (key != null && key.equals(k))))
                return first;       //如果存在table[hash]且table[hash]就是那个匹配的key,则return value
            if ((e = first.next) != null) { 
                if (first instanceof TreeNode)
                    return ((TreeNode<K,V>)first).getTreeNode(hash, key);
                do {
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        return e;
                } while ((e = e.next) != null); //如果table[hash]即first存在next,则遍历去匹配key
            }
        }
        return null;
    }

put(K key, V value) 插入操作

1、如果table == null, resize() 里面进行new 并给table赋值

2、如果table[(n - 1) & hash] 为空,空链表则直接插入

3、如果table[(n - 1) & hash] 的刚好匹配上key,执行步骤5

4、通过p.next不断遍历,如果匹配上key,则break, 执行步骤5, 返回oldValue; 否则一直遍历到链表的尾部,p.next为空的状态,则将p.next指向新的Node节点。

5、如果有匹配的key,则用value替代oldValue, 返回oldValue

    public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }

    final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
        Node<K,V>[] tab; Node<K,V> p; int n, i;
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;     //见解释1
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);   //见解释2
        else {
            Node<K,V> e; K k;
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;    //见解释3
            else if (p instanceof TreeNode)
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            else {
                for (int binCount = 0; ; ++binCount) {   //见解释4
                    if ((e = p.next) == null) {
                        p.next = newNode(hash, key, value, null);
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                            treeifyBin(tab, hash);
                        break;
                    }
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    p = e;
                }
            }
            if (e != null) { // existing mapping for key,见解释5
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }
        ++modCount;
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }

Jdk1.7之前是头插法

  Entry<K,V> e = table[bucketIndex];
  table[bucketIndex] = new Entry<K,V>(hash, key, value, e);

JDK1.8 是尾插法

if ((e = p.next) == null) {
    p.next = newNode(hash, key, value, null);
}

resize() 扩容

包括第一次的初始化操作和扩容(2倍操作)。如果table为null,根据初始容量分配内存;不为空需要扩容时,因为我们使用的是2的整数次幂扩容,以前的Node要么存放在相同的bucketIndex位置,要么存放在bucketIndex * 2^n位置。

/**
     * Initializes or doubles table size.  If null, allocates in
     * accord with initial capacity target held in field threshold.
     * Otherwise, because we are using power-of-two expansion, the
     * elements from each bin must either stay at same index, or move
     * with a power of two offset in the new table.
     *
     * @return the table
     */
 final Node<K,V>[] resize() {
        Node<K,V>[] oldTab = table;
        int oldCap = (oldTab == null) ? 0 : oldTab.length;
        int oldThr = threshold;
        int newCap, newThr = 0;
        if (oldCap > 0) {
            if (oldCap >= MAXIMUM_CAPACITY) {
                threshold = Integer.MAX_VALUE;
                return oldTab;
            }
            else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                     oldCap >= DEFAULT_INITIAL_CAPACITY)
                newThr = oldThr << 1; // double threshold
        }
        else if (oldThr > 0) // initial capacity was placed in threshold
            newCap = oldThr;
        else {               // zero initial threshold signifies using defaults
            newCap = DEFAULT_INITIAL_CAPACITY;
            newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
        }
        if (newThr == 0) {
            float ft = (float)newCap * loadFactor;
            newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
                      (int)ft : Integer.MAX_VALUE);
        }
        threshold = newThr;
        @SuppressWarnings({"rawtypes","unchecked"})
            Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap]; //真正分配存储空间
        table = newTab;
        if (oldTab != null) {
            for (int j = 0; j < oldCap; ++j) {
                Node<K,V> e;
                if ((e = oldTab[j]) != null) {c
                    oldTab[j] = null;
                    if (e.next == null)
                        newTab[e.hash & (newCap - 1)] = e;
                    else if (e instanceof TreeNode)
                        ((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
                    else { // preserve order
                        Node<K,V> loHead = null, loTail = null;
                        Node<K,V> hiHead = null, hiTail = null;
                        Node<K,V> next;
                        do {
                            next = e.next;
                            if ((e.hash & oldCap) == 0) {
                                if (loTail == null)
                                    loHead = e;
                                else
                                    loTail.next = e;
                                loTail = e;
                            }
                            else {
                                if (hiTail == null)
                                    hiHead = e;
                                else
                                    hiTail.next = e;
                                hiTail = e;
                            }
                        } while ((e = next) != null);
                        if (loTail != null) {
                            loTail.next = null;
                            newTab[j] = loHead;
                        }
                        if (hiTail != null) {
                            hiTail.next = null;
                            newTab[j + oldCap] = hiHead;
                        }
                    }
                }
            }
        }
        return newTab;
    }

remove(Object k) 删除操作

1、如果table不为null且table[(n - 1) & hash]不为空,取出table[(n - 1) & hash] 为p,p为表头;

2.1、如果p刚好能够匹配key,将p赋给node, 执行步骤3;

2.2、否则遍历,此时p会更新为e的上一个节点,如果找到能匹配上的key,e赋值给node,break,执行步骤3(也许不存在匹配的key,则直接返回null)

3、存在node(可匹配上key的这么一个节点),如果node是表头,则table[index] = node.next;否则p.next = node.next,返回node

4、返回 null

    public V remove(Object key) {
        Node<K,V> e;
        return (e = removeNode(hash(key), key, null, false, true)) == null ?
            null : e.value;
    }

   
    final Node<K,V> removeNode(int hash, Object key, Object value,
                               boolean matchValue, boolean movable) {
        Node<K,V>[] tab; Node<K,V> p; int n, index;
        if ((tab = table) != null && (n = tab.length) > 0 &&
            (p = tab[index = (n - 1) & hash]) != null) {    //步骤1
            Node<K,V> node = null, e; K k; V v;
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                node = p;    //步骤2.1
            else if ((e = p.next) != null) {
                if (p instanceof TreeNode)
                    node = ((TreeNode<K,V>)p).getTreeNode(hash, key);
                else {
                    do {    //步骤2.2
                        if (e.hash == hash &&
                            ((k = e.key) == key ||
                             (key != null && key.equals(k)))) {
                            node = e;
                            break;
                        }
                        p = e;
                    } while ((e = e.next) != null);
                }
            }
            if (node != null && (!matchValue || (v = node.value) == value ||
                                 (value != null && value.equals(v)))) {    //步骤3
                if (node instanceof TreeNode)
                    ((TreeNode<K,V>)node).removeTreeNode(this, tab, movable);
                else if (node == p)
                    tab[index] = node.next;
                else
                    p.next = node.next;
                ++modCount;
                --size;
                afterNodeRemoval(node);
                return node;
            }
        }
        return null;     //步骤4
    }

hash(Object key) 二次哈希

如果key为null,则经过hash计算的bucketIndex为0;二次哈希让键值对均匀分布在数组的N个位置之中。

 static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }

HashMap总结:

可接受空值和空键,空键会默认存储在bucketIndex为0的地方,

key值重复会覆盖,put(K key, V value) 返回oldValue;

没有实现同步,是线程不安全的,相对也就效率更快

结构:一个数组Node<K, V>[] table, 每一个Node节点是一个单链表 (数组存储空间连续,寻址快,插入删除慢;链表存储空间离散,寻址慢,插入删除快)

存储对象 put(K key, V value):根据key的HashCode()值得到数组中的bucket位置,用来存储键值对,当这个bucket位置没有存储过任何内容时,则直接存放;若已经有人占了位置,即两个key的HashCode()值相同,即产生了哈希冲突(碰撞),具有同样hashCode()的键值对会存放在同一个bucket位置;假如存在 key 的 quals() 也相同的情况下,则标记为重复键,用新的value 值替代旧的 value值,并返回旧的value值; 否则的话,每个新进来的node对象放在链表的尾部,形成单链表,返回null 。。。。  ,

取值 get(v key) : 根据key的HashCode()找到bucket位置,如果存在多个,遍历链表,对key的equals() 进行匹配,匹配成功的则返回value。

String 源码实现了hashCode() 和 equals方法,所以用的多

扩容:对数组进行扩容,当存储容量大于 loadFactor(负载因子)* 当前容量capacity时,会创建一个两倍大小容量的bucket位置,将旧的数组 移动到 新的数组中去。(多线程的情况下会产生条件竞争,同时扩容,不适用多线程情况)