JAVA8 hashmap源码阅读笔记(红黑树链表)

来源:互联网 发布:刷粉丝的软件 编辑:程序博客网 时间:2024/05/18 18:47

一:hashmap的13 个成员变量

  1. static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;
    -> 数组默认初始容量:16
  2. static final int MAXIMUM_CAPACITY = 1 << 30;
    -> 数组最大容量2 ^ 30 次方
  3. static final float DEFAULT_LOAD_FACTOR = 0.75f;
    -> 默认负载因子的大小:0.75
  4. static final int MIN_TREEIFY_CAPACITY = 64;
    -> 树形最小容量:哈希表的最小树形化容量,超过此值允许表中桶转化成红黑树
  5. static final int TREEIFY_THRESHOLD = 8;
    -> 树形阈值:当链表长度达到8时,将链表转化为红黑树
  6. static final int UNTREEIFY_THRESHOLD = 6;
    -> 树形阈值:当链表长度小于6时,将红黑树转化为链表
  7. transient int modCount; -> hashmap修改次数
  8. int threshold; -> 可存储key-value 键值对的临界值 需要扩充时;值 = 容量 * 加载因子
  9. transient int size; 已存储key-value 键值对数量
  10. final float loadFactor; -> 负载因子
  11. transient Set< Map.Entry< K,V >> entrySet; -> 缓存的键值对集合
  12. transient Node< K,V>[] table; -> 链表数组(用于存储hashmap的数据)

二:构造方法

    /**     * 默认无参构造方法:     * 初始容量16     * 负载因子0.75     */public HashMap() {        this.loadFactor = DEFAULT_LOAD_FACTOR;     }    /**     * 参数为初始容量     */public HashMap(int initialCapacity) {        this(initialCapacity, DEFAULT_LOAD_FACTOR); //调用HashMap(int initialCapacity, float loadFactor) 构造方法    }    /**     * 参数为初始容量 和 负载因子     */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);    }    /**     * 设置可存储的 key-value 键值对最大值     * 返回值为传入参数最接近的且大于等于的2的n次方     * 传入参数 3 -> 4     * 传入参数 5 -> 8     * 传入参数 32 -> 32     * 传入参数 33 -> 64     */    static final int tableSizeFor(int cap) {        int n = cap - 1;        n |= n >>> 1;        n |= n >>> 2;        n |= n >>> 4;        n |= n >>> 8;        n |= n >>> 16;        return (n < 0) ? 1 : (n >= 1 << 30) ? 1 << 30 : n + 1;    }    /*     * 构造一个新的 HashMap与指定的相同的映射 Map 。     */    public HashMap(Map<? extends K, ? extends V> m) {       this.loadFactor = DEFAULT_LOAD_FACTOR;       putMapEntries(m, false);   }   // 具体实现将map 内元素遍历插入hash表中    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;// ft代表 在默认负载因子下,该hashmap的容量                int t = ((ft < (float)MAXIMUM_CAPACITY) ?                         (int)ft : MAXIMUM_CAPACITY);// 相当于执行 (int)Math.floor(ft);                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);            }        }    }

三:Node< K,V > 存储结构

// 用于存储key-value键值// Map.Entry仅定义一些方法 因此不列出详细代码static class Node<K,V> implements Map.Entry<K,V> {        final int hash;        final K key;        V value;        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;        }        public final K getKey()        { return key; }        public final V getValue()      { return value; }        public final String toString() { return key + "=" + value; }        public final int hashCode() {            return Objects.hashCode(key) ^ Objects.hashCode(value);        }        public final V setValue(V newValue) {            V oldValue = value;            value = newValue;            return oldValue;        }        public final boolean equals(Object o) {            // 此处进行的地址的比较            if (o == this)                return true;            // 此处调用equal方法,若该类重写equal方法则调用重写后的equal方法            if (o instanceof Map.Entry) {                Map.Entry<?,?> e = (Map.Entry<?,?>)o;                if (Objects.equals(key, e.getKey()) &&                    Objects.equals(value, e.getValue()))                    return true;            }            return false;        }    }

四:put方法

    /**     * K - key(键) V - Value (值)     */public V put(K key, V value) {        return putVal(hash(key), key, value, false, true);    }    /**     * hashcode 计算方式     * 若未重写hashcode方法 则调用object的hashcode方法     * 涉及数据结构红黑树 再此不详细讲解     * 当容量达到64 且 单个位置链表长度达到8 链表转化红黑树     * 若 单个位置链表长度减小到6 将红黑树转化会链表     */static final int hash(Object key) {        int h;        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);    }     /**     * 插入key-value 键值对具体实现     */     final V putVal(int hash, K key, V value, boolean onlyIfAbsent,                   boolean evict) {        Node<K,V>[] tab; Node<K,V> p; int n, i;        // 判断 若hashmap内没有值 则重构hashmap        if ((tab = table) == null || (n = tab.length) == 0)            n = (tab = resize()).length;        // 若指定位置hashcode 未被占用 则直接将该键值对插入        if ((p = tab[i = (n - 1) & hash]) == null)            tab[i] = newNode(hash, key, value, null);        // 发生冲突时 解决方法        else {            Node<K,V> e; K k;            // 若地址相同 直接新值替换旧值            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);                        // 若此时链表内长度大于等于7 将链表转化为红黑树 并将节点插入                        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;    }    /**     * 调整底层用于存储数据的hashmap底层数组长度     * 优化操作效率 -> 每次扩容 扩大为原来的2倍     */    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        }        // 如果旧容量为 0 ,并且旧阈值>0,说明之前创建了哈希表但没有添加元素,初始化容量等于阈值        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);        }         // 如果新的阈值为 0 ,就得用 新容量*加载因子 重计算一次        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) {                    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;    }

五:get方法

    /**     * 传入key值返回value值     * 若不存在则返回null     */      public V get(Object key) {        Node<K,V> e;        return (e = getNode(hash(key), key)) == null ? null : e.value;    }    // 具体实现get-value 方法     final Node<K,V> getNode(int hash, Object key) {        Node<K,V>[] tab; Node<K,V> first, e; int n; K k;        // 若表不为空且长度不为0 且指定位置hash表内有元素        if ((tab = table) != null && (n = tab.length) > 0 && (first = tab[(n - 1) & hash]) != null) {        // 若key值相同 返回该节点            if (first.hash == hash && // always check first node((k = first.key) == key || (key != null && key.equals(k))))                return first;            // 若该节点有下一个节点 且该节点属于红黑树节点            // 按照红黑树高效查找            if ((e = first.next) != null) {                if (first instanceof TreeNode)                    return ((TreeNode<K,V>)first).getTreeNode(hash, key);                // 直到下一个节点为空 循环 对比key值                do {                    if (e.hash == hash &&                        ((k = e.key) == key || (key != null && key.equals(k))))                        return e;                } while ((e = e.next) != null);            }        }        // 若数组不存在hash算法的值 返回null        return null;    }

六:remove 方法

    /**     * 传入key 移除该key-value键值对     * 若不存在 key 返回null     */    public V remove(Object key) {        Node<K,V> e;        return (e = removeNode(hash(key), key, null, false, true)) == null ?            null : e.value;    }    // 具体实现 remove - key 方法    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;         // 若表不为空且长度不为0 且指定位置hash表内有元素        if ((tab = table) != null && (n = tab.length) > 0 && (p = tab[index = (n - 1) & hash]) != null) {            Node<K,V> node = null, e; K k; V v;            // 若key值相同 保留该节点            if (p.hash == hash &&                ((k = p.key) == key || (key != null && key.equals(k))))                node = p;            else if ((e = p.next) != null) {                // 若该节点属于红黑树 按照红黑树查找方式                 if (p instanceof TreeNode)                    node = ((TreeNode<K,V>)p).getTreeNode(hash, key);                else {                    // 循环链表直到链表为空 依次对比key 若相同 保留该节点                    do {                        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)))) {                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;            }        }        // 若数组不存在hash算法的值 返回null        return null;    }

七:putAll方法

    /**     *  参数为map 要求key-value      *  对应的泛型要求 K -key(本类或子类)V -value(本类或子类)     */    public void putAll(Map<? extends K, ? extends V> m) {        putMapEntries(m, true);    }    // 具体插入实现    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);            }        }    }

源码阅读到此结束:以下是我对hashmap自己的一些理解

  1. hashmap基于哈希表的 map接口的实现。此实现提供所有可选的映射操作,并允许使用 null 值和 null 键。与hashtable区别是hashmap允许使用null作为key值,且线程不安全,hashtable不允许null作为key值线程安全,可以使用Collections.synchronizedMap使hashmap线程安全,在JDK1.5后建议使用ConcurrentHashMap,ConcurrentHashMap采用锁分段机制,hashtable是一个线程访问时,其他线程无法访问,但ConcurrentHashMap是一个线程访问某个指定数组的某一个下标,该下标所在段不允许其他线程访问,其他线程仍可访问ConcurrentHashMap的其他下标。
  2. hashmap底层数据结构是基于数组和链表(红黑树 )来实现的,它之所以有相当快的查询速度主要是因为它是通过计算散列码来决定存储的位置。通过key值计算hash码值,将其传递进数组,若hash码值冲突则采用链表连接,若该hashmap容量大于64且该链表长度大于8则将该链表转化为红黑树,若链表长度减少到6时候,则将红黑树转化回链表
  3. hashmap每次扩容扩大为原来的两倍,但扩容操作需要将数据全部重新计算放入新表,很消耗资源,如果对数据含量有一定预估,建议初始化hashmap时指定容量

阅读完源码:感觉自己萌萌哒,看一看面试题吧!

1、“你知道HashMap的工作原理吗?” “你知道HashMap的get()方法的工作原理吗?”

  HashMap是基于hashing的原理,我们使用put(key, value)存储对象到HashMap中,使用get(key)从HashMap中获取对象。当我们给put()方法传递键和值时,我们先对键调用hashCode()方法,返回的hashCode用于找到bucket位置来储存Entry对象。

2、“当两个对象的hashcode相同会发生什么?”

  因为hashcode相同,所以它们的bucket位置相同,‘碰撞’会发生。因为HashMap使用LinkedList存储对象,这个Entry(包含有键值对的Map.Entry对象)会存储在LinkedList中。(当向 HashMap 中添加 key-value 对,由其 key 的 hashCode() 返回值决定该 key-value 对(就是 Entry 对象)的存储位置。当两个 Entry 对象的 key 的 hashCode() 返回值相同时,将由 key 通过 eqauls() 比较值决定是采用覆盖行为(返回 true),还是产生 Entry 链(返回 false)。),此时若你能讲解JDK1.8红黑树引入,面试官或许会刮目相看。

3、“如果两个键的hashcode相同,你如何获取值对象?”

  当我们调用get()方法,HashMap会使用键对象的hashcode找到bucket位置,然后获取值对象。如果有两个值对象储存在同一个bucket,将会遍历LinkedList直到找到值对象。找到bucket位置之后,会调用keys.equals()方法去找到LinkedList中正确的节点,最终找到要找的值对象。(当程序通过 key 取出对应 value 时,系统只要先计算出该 key 的 hashCode() 返回值,在根据该 hashCode 返回值找出该 key 在 table 数组中的索引,然后取出该索引处的 Entry,最后返回该 key 对应的 value 即可。)

4、“如果HashMap的大小超过了负载因子(load factor)定义的容量,怎么办?”

  当一个map填满了75%的bucket时候,和其它集合类(如ArrayList等)一样,将会创建原来HashMap大小的两倍的bucket数组,来重新调整map的大小,并将原来的对象放入新的bucket数组中。这个过程叫作rehashing,因为它调用hash方法找到新的bucket位置。

5、“你了解重新调整HashMap大小存在什么问题吗?”

  当重新调整HashMap大小的时候,确实存在条件竞争,因为如果两个线程都发现HashMap需要重新调整大小了,它们会同时试着调整大小。在调整大小的过程中,存储在LinkedList中的元素的次序会反过来,因为移动到新的bucket位置的时候,HashMap并不会将元素放在LinkedList的尾部,而是放在头部,这是为了避免尾部遍历(tail traversing)。如果条件竞争发生了,那么就死循环了。这个时候,你可以质问面试官,为什么这么奇怪,要在多线程的环境下使用HashMap呢?

原创粉丝点击