HashMap源码解析

1.HashMap结构

HashMap使用的是数组加链表的形式,数组里面存储的是key-value,在java8中为Node。

public class HashMap extends AbstractMap
    implements Map, Cloneable, Serializable {
    //序列号
    private static final long serialVersionUID = 362498820763181265L;
   //HashMap 默认数组大小,1左移4位 = 1*2^4 = 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;
    //某个桶的链表长度大于8时 会转换为红黑树
    static final int TREEIFY_THRESHOLD = 8;
   //某个桶的长度小于6时,会转换为链表 前提是红黑树结构
    static final int UNTREEIFY_THRESHOLD = 6;
  //当HashMap中元素大于64时,会转换为红黑树
    static final int MIN_TREEIFY_CAPACITY = 64;
   //存储元素的数组
    transient Node[] table;
    //将数据转换成set的另一种存储形式,这个变量主要用于迭代功能。
    transient Set> entrySet;
   //元素数量
    transient int size;
   //统计map修改的次数
    transient int modCount;
    //临界值
    int threshold;
   //加载因子
    final float loadFactor;

2.为什么初始化大小为16,扩容因子为0.75?

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

用位与运算的方式和取模的方式结果一样,而且效率较高。index的计算方式为数组长度-1 &hash, 如果数组长度为2的次幂,则n-1的二进制为11111,这时候index的结果就等于Hashcode的后几位值。只要HashCode分布均匀那么Hash后的结果就均匀。
扩容因子是0.75是为了提高空间利用率和 减少查询成本的折中,主要是泊松分布,0.75的话碰撞最小,

3.获取Hash值方法

    static final int hash(Object key) {
        int h;
    //先进行无符号右移16位然后异或hashcode 主要是为了减少hash冲突,加上一个干扰因子。
       return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }

4.put方法

    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) {
       //tab:hash数组 p 桶的首节点 n HashMap的长度 i计算出数组的下标
        Node[] tab; Node p; int n, i;
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
       //如果计算出hash位置没有冲突,此时p节点指向桶中首节点的位置
        if ((p = tab[i = (n - 1) & hash]) == null)
          //将key-value的值放在此处
            tab[i] = newNode(hash, key, value, null);
        else {
          //存在Hash冲突的情况 e 临时节点 k 存放当前节点key
            Node e; K k;
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                 //如果key的hash值相等,并且key也相等 将此时桶中首节点的值赋值给节点e等待value覆盖
                e = p;
            else if (p instanceof TreeNode)
              //如果hash值不等于首节点,判断是否是红黑树节点
                e = ((TreeNode)p).putTreeVal(this, tab, hash, key, value);
            else {
               //不属于红黑树节点则循环链表遍历 此时p指向桶中首节点的位置
                for (int binCount = 0; ; ++binCount) {
                  //找到链表尾节点,此时桶中链表的所有节点的key和新加入的key的不相等,并且hash值也不相等,则将Key-Value添加到链表的最后
                    if ((e = p.next) == null) {
                        p.next = newNode(hash, key, value, null);
                      //判断此时链表长度是否大于8 是否转化为红黑树
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                            treeifyBin(tab, hash);
                        break;
                    }
                    //如果key的hash值相等,并且key也相等跳出循环
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    p = e;
                }
            }
          //有重复的key,使用value将旧值覆盖掉 并且返回旧值
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }
        //执行到此处表示没有重复的key 表示修改了多少次
        ++modCount;
      //判断是否大于临界值,大于则进行扩容
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }

3.remove方法

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

 final Node removeNode(int hash, Object key, Object value,
                               boolean matchValue, boolean movable) {
        Node[] tab; Node p; int n, index;
      //如果table数组不为空 并且数组长度大于0 并且hash值对应数组中的下标出有数据
        if ((tab = table) != null && (n = tab.length) > 0 &&
            (p = tab[index = (n - 1) & hash]) != null) {
            Node node = null, e; K k; V v;
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
              //要删除的节点刚好是桶的首节点,赋值p给node
                node = p;
          //不是桶的首节点
            else if ((e = p.next) != null) {
                //如果是红黑树节点,采用红黑树的方式查找节点
                if (p instanceof TreeNode)
                    node = ((TreeNode)p).getTreeNode(hash, key);
                else {
                    do {
                        //一直循环链表,直到找到相同的key
                        if (e.hash == hash &&
                            ((k = e.key) == key ||
                             (key != null && key.equals(k)))) {
                            //找到相同的key 赋值给节点node
                            node = e;
                            break;
                        }
                        //此时p已经指向删除节点的上一个节点,下面会用到p节点
                        p = e;
                    } while ((e = e.next) != null);
                }
            }
            if (node != null && (!matchValue || (v = node.value) == value ||
                                 (value != null && value.equals(v)))) {
              //如果节点是红黑树节点 使用红黑树的方式删除
                if (node instanceof TreeNode)
                    ((TreeNode)node).removeTreeNode(this, tab, movable);
                //如果node节点等于桶的首节点,此时将桶中index位置指向node节点的下一个节点
                else if (node == p)
                    tab[index] = node.next;
                else
                    //如果被删除节点不是桶中首节点,则节点p指向node的下一个节点 删除节点node
                    p.next = node.next;
              //计数器修改
                ++modCount;
              //HashMap size--
                --size;
                afterNodeRemoval(node);
                //返回删除节点
                return node;
            }
        }
        //删除失败,返回null
        return null;
    }

获取元素

    public V get(Object key) {
        Node e;
        return (e = getNode(hash(key), key)) == null ? null : e.value;
    }
    final Node getNode(int hash, Object key) {
      //tab指向数组 first节点首次指向桶中首节点 k桶中节点的key
        Node[] tab; Node first, e; int n; K k;
        //判断数组是否为null并且判断长度是否大于0,数组index出节点是否为空
        if ((tab = table) != null && (n = tab.length) > 0 &&
            (first = tab[(n - 1) & hash]) != null) {
            if (first.hash == hash && //如果桶中首节点的key和查询的key相同直接返回桶中首节点
                ((k = first.key) == key || (key != null && key.equals(k))))
                return first;
            if ((e = first.next) != null) {
                //如果是红黑树节点
                if (first instanceof TreeNode)
                    //使用红黑树方法查询
                    return ((TreeNode)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;
    }

你可能感兴趣的:(HashMap源码解析)