关于java:JDK18-HashMap解析

6次阅读

共计 8992 个字符,预计需要花费 23 分钟才能阅读完成。

数据结构

JDK1.8 的 HashMap 采纳数组 + 单链表 + 红黑树的数据结构,数组和链表存储的是一个个 Node 对象,红黑树存储的是 TreeNode 对象

Node

    static class Node<K,V> implements Map.Entry<K,V> {
        final int hash;
        final K key;
        V value;
        Node<K,V> next;
    }

TreeNode

    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);
        }

        final TreeNode<K,V> root() {for (TreeNode<K,V> r = this, p;;) {if ((p = r.parent) == null)
                    return r;
                r = p;
            }
        }
    }

罕用办法

罕用 API

V get(Object key); // 取得指定 key 的值
V put(K key, V value);  // 增加 key-value 对
void putAll(Map<? extends K, ? extends V> m);  // 将指定 Map 中的 key-value 对复制到此 Map 中
V remove(Object key);  // 删除该 key-value

boolean containsKey(Object key); // 判断是否存在该 key 的 key-value 对;是则返回 true
boolean containsValue(Object value);  // 判断是否存在该 value 的 key-value 对;是则返回 true
 
Set<K> keySet();  // 独自抽取 key 序列,将所有 key 生成一个 Set
Collection<V> values();  // 独自 value 序列,将所有 value 生成一个 Collection

void clear(); // 革除 HashMap 中的所有 key-value 对
int size();  // 返回 HashMap 中所有 key-value 对的数量
boolean isEmpty(); // 判断 HashMap 是否为空,size == 0 时示意为空 

应用

public class HashMapTest {public static void main(String[] args) {
      /**
        * 1. 申明 1 个 HashMap 的对象
        */
        Map<String, Integer> map = new HashMap<String, Integer>();

      /**
        * 2. 向 HashMap 增加数据(放入键 - 值对)*/
        map.put("Java", 1);
        map.put("HashMap", 2);
        map.put("List",3);
        map.put("set",4);

       /**
        * 3. 获取 HashMap 的某个数据
        */
        System.out.println(""+ map.get("HashMap"));

      /**
        * 4. 遍历 HashMap 共有 3 种办法:别离针对 Entry 或 key 或 value
        * 步骤 1:取得 Entry 或 key 或 value 的汇合
        * 步骤 2:遍历,应用 for 循环或迭代器 Iterator
        */

        // 办法 1:取得 Entry 的 Set 汇合再遍历
        // 取得 Entry 的 Set 汇合
        Set<Map.Entry<String, Integer>> entrySet = map.entrySet();
        // 通过 for 循环遍历
        for(Map.Entry<String, Integer> entry : entrySet){System.out.print(entry.getKey());
            System.out.println(entry.getValue());
        }
        // 通过迭代器遍历
        // 先取得 Entry 的 Iterator,再循环遍历
        Iterator iter1 = entrySet.iterator();
        while (iter1.hasNext()) {
            // 遍历时,需先获取 entry,再别离获取 key、value
            Map.Entry entry = (Map.Entry) iter1.next();
            System.out.print((String) entry.getKey());
            System.out.println((Integer) entry.getValue());
        }


        // 办法 2:取得 key 的 Set 汇合再遍历
        Set<String> keySet = map.keySet();
        // 通过 for 循环
        for(String key : keySet){System.out.print(key);
            System.out.println(map.get(key));
        }
        // 通过迭代器遍历
        // 先取得 key 的 Iterator,再循环遍历
        Iterator iter2 = keySet.iterator();
        String key = null;
        while (iter2.hasNext()) {
            // 遍历时,需先获取 key,再获取 value
            key = (String)iter2.next();
            System.out.print(key);
            System.out.println(map.get(key));
        }


        // 办法 3:取得 value 的汇合再遍历
        Collection valueSet = map.values();
        // 取得 values 的 Iterator,再循环遍历
        Iterator iter3 = valueSet.iterator();
        while (iter3.hasNext()) {System.out.println(iter3.next());
        }

    }
}

对于遍历形式,举荐应用针对 key-value 对(Entry)的形式:效率高

  1. 对于遍历 keySet,valueSet,本质上遍历了 2 次:
    第 1 次,for/iterator 迭代器遍历;
    第 2 次 从 HashMap 中取出 key 的 value 操作
  2. 对于遍历 entrySet,本质遍历了 1 次 for/iterator 迭代器遍历,Entry 曾经存储了 key 和 value

源码剖析

次要属性

// 默认容量
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;
// 最大容量
static final int MAXIMUM_CAPACITY = 1 << 30;
// 加载因子
static final float DEFAULT_LOAD_FACTOR = 0.75f;
// 扩容阈值 = 容量 x 加载因子,当哈希表的大小 ≥ 扩容阈值时,就会扩容哈希表
int threshold
// 存储数据的 Node 类型数组,长度 = 2 的幂
transient Node<K,V>[] table;
//HashMap 中存储的键值对的数量
transient int size


// 链表的树化阈值,即链表转成红黑树的阈值,当 Node 链表长度 > 该值时,则将链表转换成红黑树
static final int TREEIFY_THRESHOLD = 8; 
// 链表的还原阈值,即红黑树转为链表的阈值,当在扩容时,HashMap 的数据存储地位会从新计算,在从新计算存储地位后,当红黑树内 TreeNode 数量 < 6 时,则将 红黑树转换成链表
static final int UNTREEIFY_THRESHOLD = 6;
// 最小链表树化容量阈值,即 当 Node 数组长度 > 该值时,才容许树形化链表,否则则间接扩容,而不是树形化
static final int MIN_TREEIFY_CAPACITY = 64;

构造方法

    // 加载因子,容量可指定
    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);
    }

    // 加载因子等于默认值,容量可指定  
    public HashMap(int initialCapacity) {this(initialCapacity, DEFAULT_LOAD_FACTOR);
    }

    // 默认构造函数,加载因子,容量等于默认值
    public HashMap() {this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted}

    // 可传入一个 map 的构造函数
    public HashMap(Map<? extends K, ? extends V> m) {
        this.loadFactor = DEFAULT_LOAD_FACTOR;
        putMapEntries(m, false);
    }

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) {Node<K,V>[] tab; Node<K,V> p; int n, i;
        //1. 若 Node 数组为空,则通过 resize()初始化数组
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
        //2. 计算 key 寄存 Node 数组中的数组下标,判断这个数组下标 Node 数组上是否有 Node 存在
        //2.1 若不存在,则在该地位新建一个 Node 节点    
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null)
        //2.2 若存在 
        else {
            Node<K,V> e; K k;
            //2.1.1 判断 key 是否与数组上的 Node 外面的 key 是否雷同,是则用新的 value 值替换旧的 value 值   
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;
            //2.1.2 若不雷同,判断以后 Node 是红黑树,则在树中插入或更新键值对    
            else if (p instanceof TreeNode)
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            //2.1.3 若不雷同,判断以后 Node 是链表,则在链表中插入或更新键值对     
            else {
            // 遍历以该 Node 为头结点的链表, 判断该 key 是否已存在
                for (int binCount = 0; ; ++binCount) {
                // 若该 key 不存在,则将 key-value 增加到 Node 数组中, 这里采纳尾插法
                    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;
                    }
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    p = e;
                }
            }
            // 若该 key 已存在,则用新 value 替换旧 value
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }
        ++modCount;
        // 插入胜利后,判断理论存在的键值对数量 size > 最大容量 threshold
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }

putTreeVal()

        // 向红黑树插入或更新数据(键值对),遍历红黑树判断该节点的 key 是否与传入 key 雷同,雷同则新 value 笼罩旧 value,不雷同则插入
        final TreeNode<K,V> putTreeVal(HashMap<K,V> map, Node<K,V>[] tab,
                                       int h, K k, V v) {
            Class<?> kc = null;
            boolean searched = false;
            TreeNode<K,V> root = (parent != null) ? root() : this;
            for (TreeNode<K,V> p = root;;) {
                int dir, ph; K pk;
                if ((ph = p.hash) > h)
                    dir = -1;
                else if (ph < h)
                    dir = 1;
                else if ((pk = p.key) == k || (k != null && k.equals(pk)))
                    return p;
                else if ((kc == null &&
                          (kc = comparableClassFor(k)) == null) ||
                         (dir = compareComparables(kc, k, pk)) == 0) {if (!searched) {
                        TreeNode<K,V> q, ch;
                        searched = true;
                        if (((ch = p.left) != null &&
                             (q = ch.find(h, k, kc)) != null) ||
                            ((ch = p.right) != null &&
                             (q = ch.find(h, k, kc)) != null))
                            return q;
                    }
                    dir = tieBreakOrder(k, pk);
                }

                TreeNode<K,V> xp = p;
                if ((p = (dir <= 0) ? p.left : p.right) == null) {
                    Node<K,V> xpn = xp.next;
                    TreeNode<K,V> x = map.newTreeNode(h, k, v, xpn);
                    if (dir <= 0)
                        xp.left = x;
                    else
                        xp.right = x;
                    xp.next = x;
                    x.parent = x.prev = xp;
                    if (xpn != null)
                        ((TreeNode<K,V>)xpn).prev = x;
                    moveRootToFront(tab, balanceInsertion(root, x));
                    return null;
                }
            }
        }

resize()办法

    final Node<K,V>[] resize() {Node<K,V>[] oldTab = table; // 扩容前 Node 数组
        int oldCap = (oldTab == null) ? 0 : oldTab.length; // 扩容前 Node 数组长度
        int oldThr = threshold; // 扩容前 Node 数组阈值
        int newCap, newThr = 0;
        //Node 数组长度大于 0, 非初始化数组
        if (oldCap > 0) {
            // 扩容前 Node 数组容量超过最大值,不扩容
            if (oldCap >= MAXIMUM_CAPACITY) {
                threshold = Integer.MAX_VALUE;
                return oldTab;
            }
            // 没有超过最大值,数组长度扩容为原来的 2 倍
            else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                     oldCap >= DEFAULT_INITIAL_CAPACITY)
                newThr = oldThr << 1; // double threshold
        }
        //Node 数组长度 =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);
        }
        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) {
         // 遍历旧数组,从新计算每个 Node 在新数组的数组下标,应用尾插法将旧数组中的 Node 转移到新数组
            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()办法

    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;
        // 计算 key 寄存 Node 数组中的数组下标,判断这个数组下标 Node 数组上是否有 Node 存在
        if ((tab = table) != null && (n = tab.length) > 0 &&
            (first = tab[(n - 1) & hash]) != null) {
            //1. 在 Node 数组中找 key 相等的 Node
            if (first.hash == hash && // always check first node
                ((k = first.key) == key || (key != null && key.equals(k))))
                return first;
            //2. 在红黑树中找 key 相等的 Node    
            if ((e = first.next) != null) {if (first instanceof TreeNode)
                    return ((TreeNode<K,V>)first).getTreeNode(hash, key);
                //3. 在链表中找 key 相等的 Node    
                do {
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        return e;
                } while ((e = e.next) != null);
            }
        }
        return null;
    }

源码总结

1.JDK1.8 的 HashMap 采纳数组 + 单链表 + 红黑树的数据结构,数组和链表存储的是一个个 Node 对象,红黑树存储的是 TreeNode 对象
2. 增加 key-value 时会依据 key 值计算出对应的 hash 值,再依据 hash 值计算出对应的数组下标,判断这个数组在这个下标中是否有 Node 存在:
若没有,则在该地位新建一个 Node 节点
若有则判断这个 Node 是属于链表还是属于红黑树,而后别离遍历链表或红黑树,判断是否有雷同的 key,如果有则用新 value 替换旧 value,如果没有就将 Node 增加到链表或红黑树,留神这里的链表插入采纳尾插法
3. 在将 Node 插入到链表时:
会进行是否红黑树树化的判断,链表长度 >= 桶的树化阈值 =8,则将链表转换成红黑树
会进行是否须要扩容的判断,当 Node 的数量,或者说 key-value 的数量大于扩容阈值 = 以后容量 x 加载因子,新建一个数组,容量时是数组的 2 倍,将旧 entry 数组上的 entry 数据转移到 newtable 中,让以后的数组指向新数组从而实现扩容。

4.hashmap1.8 与 hashmap1.7 的区别:
1. 数据结构不同
2. 与 1.7 中 hashmap 的扩容机制不同:
a.hashmap1.8 中的扩容后 Node 的地位是数组的原地位 / 原地位 + 旧容 b. 量,hashmap1.7 则是原来地位
b. 扩容时,hashmap1.8 采纳尾插法将数据转移到新数组中,hashmap1.7 采纳头插法

正文完
 0