HashMap-Java8源码教会你正确的使用方式

HashMap在Java中,基于散列表(hash table)实现的。其特性如下:

  1. HashMap以数组的形式存储对象,使用hash散列函数获取元素的key的hash值,然后,根据hash值获取数组的index值。
  2. HashMap使用分离链接法存储节点hash冲突的元素,使用基于单链表Node和基于红黑树的TreeNode两种方式,存储hash冲突的对象。TREEIFY_THRESHOLD和UNTREEIFY_THRESHOLD的值,定义Node与TreeNode的相互转换操作。
  3. 使用loadFactor定义填充因子,默认值为0.75,当添加元素的个数大于loadFactor设置的值,则就HashMap就需要扩容。
  4. 被加载的对象在java中必须实现int hashCode()方法和boolean equals(Object obj)方法。hashCode获取对象的散列值,equals方法比较对象大小。
  • 节点定义

HashMap中存储对象的节点包括Node基于单链表和TreeNode基于红黑树,TreeNode继承自Node。默认元素hash冲突时,元素存储在Node链表中,当Node链表中存储的个数大于默认的TREEIFY_THRESHOLD值时,存储hash冲突的表会使用TreeNode树存储。Node基于单链表方式,其的源码如下:

    /**
     * HashMap的节点定义
     */
    static class Node<K,V> implements Map.Entry<K,V> {
        
        // 缓存key的hash值,rehash时,避免计算浪费时间
        final int hash;
        final K key;
        V value;
        // hash冲突时,以单链表存储对象
        Node<K,V> next;

        Node(int hash, K key, V value, Node<K,V> next) {
            this.hash = hash;
            this.key = key;
            this.value = value;
            this.next = next;
        }

       ......
    }

 TreeNode基于红黑树(其原理可以参考红黑树(red black tree)-分分钟钟被安排地明明白白)的方式实现,其源码定义如下:

    /**
     * 红黑树节点
     */
    static final class TreeNode<K,V> extends LinkedHashMap.Entry<K,V> {
        
        TreeNode<K,V> parent;  // red-black tree links
        TreeNode<K,V> left;
        TreeNode<K,V> right;
        TreeNode<K,V> prev;    // needed to unlink next upon deletion
        // 是否为红色
        boolean red;

        TreeNode(int hash, K key, V val, Node<K,V> next) {
            super(hash, key, val, next);
        }
    }
  • 属性定义

在HashMap中,其主要的属性定义如下:

  1. Node<K,V>[] table,以节点数组的形式,存储数据。默认在添加的值的时候设置大小,其大小为16。
  2. size,存储对象的大小。
  3. loadFactor,填充因子,当集合中存储的对象大于设置的填充因子值,则进行扩容和rehash操作。

其源代码如下:

public class HashMap<K,V> extends AbstractMap<K,V>
    implements Map<K,V>, Cloneable, Serializable {

    /**
     * 默认的集合容量,值为16
     */
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16

    /**
     * 最大的集合容量
     */
    static final int MAXIMUM_CAPACITY = 1 << 30;

    /**
     * 集合负载因子
     */
    static final float DEFAULT_LOAD_FACTOR = 0.75f;

    /**
     * 使用红黑树tree替换单链表存储hash冲突的阈值
     */
    static final int TREEIFY_THRESHOLD = 8;

    /**
     * 使用单链表替换红黑树tree存储hash冲突的阈值
     */
    static final int UNTREEIFY_THRESHOLD = 6;

    /**
     * 当Map里面的数量超过这个值时,才能进行树形化 ,否则进行扩容
     */
    static final int MIN_TREEIFY_CAPACITY = 64;

    /**
     * 存储数据的节点数组
     */
    transient Node<K,V>[] table;

    /**
     * Holds cached entrySet(). Note that AbstractMap fields are used
     * for keySet() and values().
     */
    transient Set<Map.Entry<K,V>> entrySet;

    /**
     * 存储元素大小
     */
    transient int size;

    /**
     *  修改次数
     */
    transient int modCount;

    /**
     * 需要扩容的元素个数
     */
    int threshold;

    /**
     *填充因子
     */
    final float loadFactor;

    ......
}
  • put和get方法介绍

重点介绍下HashMap集合的put和get方法。添加新的元素,大致的流程如下:

  1. 以key的hash值,计算其在table数组中的位置,并设置到Node节点中。
  2. 判断元素hash是否冲突,没有冲突则元素直接添加到table数组,反之,则添加值到Node单链表中。当添加到Node单链表中hash冲突的元素个数大于TREEIFY_THRESHOLD设置的个数,则使用红黑树TreeNode存储元素。
  3. 判断集合存储的大小是否大于负载因子设置的个数,如果大于则进行扩容。扩容很消耗时间,使用中尽量开始初始化结合大小。

put方法源码如下:

public class HashMap<K,V> extends AbstractMap<K,V>
    implements Map<K,V>, Cloneable, Serializable {

   /**
     * 添加key和value值
     */
    public V put(K key, V value) {
        // hash(key)计算key的hash值
        return putVal(hash(key), key, value, false, true);
    }

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

    /**
     * 添加值
     */
    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;
        // 如果没有初始化table大小,则在添加元素时初始化大小,默认值为16
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        else {
            Node<K,V> e; K k;
            // 如果元素存在,并且hash值相同并且key也相同,则替换原值
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;
            // 树形节点,则往树中添加节点
            else if (p instanceof TreeNode)
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            else {
                for (int binCount = 0; ; ++binCount) {
                    // 单链表后添加元素
                    if ((e = p.next) == null) {
                        p.next = newNode(hash, key, value, null);
                        // 单链表存储元素的数量大于TREEIFY_THRESHOLD设置的值,则使用红黑树存储
                        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
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }
        ++modCount;
        // 如果集合存储元素大小大于负载因子允许的限制,则集合扩容
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }

    /**
     * 使用红黑树TreeNode替换单链表Node存储hash冲突元素
     */
    final void treeifyBin(Node<K,V>[] tab, int hash) {
        int n, index; Node<K,V> e;
        // 如果table的容量小于MIN_TREEIFY_CAPACITY的限制值,则进行扩容
        if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
            resize();
        else if ((e = tab[index = (n - 1) & hash]) != null) {
            // 使用TreeNode存储
            TreeNode<K,V> hd = null, tl = null;
            do {
                TreeNode<K,V> p = replacementTreeNode(e, null);
                if (tl == null)
                    hd = p;
                else {
                    p.prev = tl;
                    tl.next = p;
                }
                tl = p;
            } while ((e = e.next) != null);
            if ((tab[index] = hd) != null)
                hd.treeify(tab);
        }
    }

}

从HashMap中获取元素,比较简单,其流程如下:

  1. 对key进行函数hash,根据hash值计算出table数组中元素的位置。
  2. 如果hash值有冲突,则首先判断冲突表的中第一个元素。然后,从单链表Node或者TreeNode红黑树中获取指定元素。

get方法的源码如下:

   /**
     * 获取元素
     */
    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) {
            // 判断第一个元素
            if (first.hash == hash && // always check first node
                ((k = first.key) == key || (key != null && key.equals(k))))
                return first;
            // 从单链表中获取元素
            if ((e = first.next) != null) {
                // 从TreeNode 获取元素
                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);
            }
        }
        return null;
    }
发布了37 篇原创文章 · 获赞 2 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/new_com/article/details/104464809
今日推荐