zoukankan      html  css  js  c++  java
  • java集合框架(一):HashMap

      有大半年没有写博客了,虽然一直有在看书学习,但现在回过来看读书基本都是一种知识“输入”,很多时候是水过无痕。而知识的“输出”会逼着自己去找出没有掌握或者了解不深刻的东西,你要把一个知识点表达出来,自己没有吃透是很难写出来的。我算是明白了为什么有些人可以通过写博客来学习,我也不能懒了,坚持写下去。

      都以为自己对java的集合框架掌握得还可以,打开源码才发现我只是掌握了他们的基本使用,而对原理和数据结构方面只是略知一二。接下来的一段时间里,我会写一个专题详细总结java集合框架知识,首先从HashMap开始吧。

          HashMap是以Key-Value方式存储数据,Key用散列函数映射到table数组(散列表),解决冲突的方法是分离链接法。即HashMap的数据结构是:数组+链表+红黑树(java8增加了红黑树),其结构图如下:

    一、类的定义

    HashMap继承抽象类AbstractMap,实现了Map接口。抽象类AbstractMap实现了接口Map的部分方法,这样子类就可以通过继承而共用这些方法,而无须再次实现了。

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

    二、存储结构

    从上面的分析,我们知道HashMap的基本存储单元是Node<K,V>,它保存一个Key-Value。每个Node通过哈希函数映射到哈希桶数组,在源码中用Node<K,V>[] table表示哈希桶数组。下面来看看Node的源码(本文源码都是基于java8):

    static class Node<K,V> implements Map.Entry<K,V> {
            final int hash;    //用来定位数组索引位置
            final K key;
            V value;
            Node<K,V> next;   //链表的下一个node
     
            Node(int hash, K key, V value, Node<K,V> next) { ... }
            public final K getKey(){ ... }
            public final V getValue() { ... }
            public final String toString() { ... }
            public final int hashCode() { ... }
            public final V setValue(V newValue) { ... }
            public final boolean equals(Object o) { ... }
    }

    三、构造函数

    构造函数需要对下面几个参数初始化(部分使用默认的)

    Node<K,V>[] table; // 哈希桶数组

    int threshold;// 所能容纳的key-value对极限,大于这个阀值将会进行扩容

    final float loadFactor;  // 负载因子

    int modCount; // 记录修改的次数

    int size; // key-value对的个数

    1.无参构造器

    public HashMap() {
        this.loadFactor = DEFAULT_LOAD_FACTOR; // 初始化默认负载因子为0.75
    }

    负载因子决定哈希桶数组的疏密程度,太疏会造成空间浪费,太密容易形成哈希冲突,一般使用默认的。

    2.指定哈希桶数组初始容量构造器

    public HashMap(int initialCapacity) {
        this(initialCapacity, DEFAULT_LOAD_FACTOR);// 调用两个参数的构造器
    }

    3.指定哈希桶数组初始容量和负载因子构造器

    public HashMap(int initialCapacity, float loadFactor) {
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal initial capacity: " +
                                               initialCapacity);
        if (initialCapacity > MAXIMUM_CAPACITY)
            initialCapacity = MAXIMUM_CAPACITY;
       // 小于0或者不是数字时抛出异常
        if (loadFactor <= 0 || Float.isNaN(loadFactor))
            throw new IllegalArgumentException("Illegal load factor: " +
                                               loadFactor);
        this.loadFactor = loadFactor;
        this.threshold = tableSizeFor(initialCapacity);//确保阀值为大于给定初始容量的最小2的n次幂,比如给定初始容量为9,则阀值为16(2的4次幂),给定为25,则为32(2的5次幂)
    }

    四、存储实现

    1.put方法

     public V put(K key, V value) {
          // 对key的hashCode()做hash
          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;
           // tab为空则创建
            if ((tab = table) == null || (n = tab.length) == 0)
                n = (tab = resize()).length;
           // 通过hash计算数组index,如果index位置没有元素则直接插入Node对象
            if ((p = tab[i = (n - 1) & hash]) == null)
                tab[i] = newNode(hash, key, value, null);
           // index对应位置已经有元素了,说明hash碰撞了,则需要构建链表或者红黑树
            else {
                Node<K,V> e; K k;
              // hash和key都相等,可以当成是同一个对象,这时要么覆盖原来的value,要么继续使用原来的value
                if (p.hash == hash &&
                    ((k = p.key) == key || (key != null && key.equals(k))))
                    e = p;
              // index位置已经有红黑树了,加入新的节点
                else if (p instanceof TreeNode)
                    e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
              // 在index位置构建链表
                else {
                  // 遍历链表,把新的节点加入到表尾部
                    for (int binCount = 0; ; ++binCount) {
                        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;
                        }
                       // 链表中有相同的hash和key,退出遍历
                        if (e.hash == hash &&
                            ((k = e.key) == key || (key != null && key.equals(k))))
                            break;
                        p = e;
                    }
                }
                // 链表或者红黑树中存在相同的key,判断要不要覆盖
                if (e != null) { // existing mapping for key
                    V oldValue = e.value;
                    if (!onlyIfAbsent || oldValue == null)
                        e.value = value;
                    // 该函数提供给LinkedHashMap使用,维护了一个访问链表
                    afterNodeAccess(e);
                    return oldValue;
                }
            }
            // 修改数加1,为多线程遍历提供fast-fail机制
            ++modCount;
            // 判断是否需要扩容
            if (++size > threshold)
                resize();
            // 该函数提供给LinkedHashMap使用,维护了一个插入顺序的双向链表
            afterNodeInsertion(evict);
            return null;
        }

    2.get方法

    get操作其实就是通过哈希值算出节点所在table数组的位置,然后判断是链表还是红黑树或者是刚好是要找的值

    public V get(Object key) {
        Node<K,V> e;
        return (e = getNode(hash(key), key)) == null ? null : e.value;
    }
    
    // 这纯粹是一个数学方法,>>>表示符号向右移动,假如有符号位-8表示为11000,则-8 >>> 2 == 5,把符号位也当成了数值
    static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }
    
    final Node<K,V> getNode(int hash, Object key) {
        Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
      // 通过hash值计算index位置
        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) {
           // 红黑树中查找
                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;
    }

    五、遍历实现

    遍历操作在内部抽象类HashIterator中实现,其实也是通过迭代器完成的,使用fast-fail机制保证遍历时map不会改变。遍历的迭代器会继承HashIterator。

    public Set<Map.Entry<K,V>> entrySet() {
        Set<Map.Entry<K,V>> es;
        return (es = entrySet) == null ? (entrySet = new EntrySet()) : es;
    }
    
    abstract class HashIterator {
        Node<K,V> next;        // next entry to return
        Node<K,V> current;     // current entry
        int expectedModCount;  // for fast-fail
        int index;             // current slot
        // 初始化参数
        HashIterator() {
            expectedModCount = modCount;
            Node<K,V>[] t = table;
            current = next = null;
            index = 0;
         // index从第一个不为null的地方开始
            if (t != null && size > 0) { // advance to first entry
                do {} while (index < t.length && (next = t[index++]) == null);
            }
        }
    
        public final boolean hasNext() {
            return next != null;
        }
        // 这个方法会被迭代器next()方法调用
        final Node<K,V> nextNode() {
            Node<K,V>[] t;
            Node<K,V> e = next;
         // fast-fail判断,避免遍历的时候map有发生改变
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
            if (e == null)
                throw new NoSuchElementException();
         // 判读当前index位置是否还有下一个节点,就把下一个节点放到next,否则遍历table数组
            if ((next = (current = e).next) == null && (t = table) != null) {
                do {} while (index < t.length && (next = t[index++]) == null);
            }
            return e;
        }
    }

    六、java8的扩容机制

    java8的扩容是做了优化的,直接看代码吧

    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) {
          // 当容量大于(1 << 30== 1073741824),让阈值等于最大整数,不再扩容,就让它碰撞吧
            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) {
        // 遍历旧table数组的元素到新的table数组
            for (int j = 0; j < oldCap; ++j) {
                Node<K,V> e;
                if ((e = oldTab[j]) != null) {
                    oldTab[j] = null;
               // 在j处只有一个节点
                    if (e.next == null)
                        newTab[e.hash & (newCap - 1)] = e;
               // 在j处是红黑树
                    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;
                       // 这里用了比较巧妙的方法,如果元素的hash值跟旧table数组的容量做按位与操作等于0,
    // 则在新table数组中元素还是映射到相同的index位置。
                  // 否则映射到j+oldCap位置。这样一来就不用重新计算每个节点的位置了,在java6,java7中需要rehash到新的位置。
    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; }

    七、总结

     至此总算把HashMap的基本原理搞清楚了,通过源码我们对HashMap可以总结出以下几点:

    1. 哈希桶的默认初始容量为16,最大为1<<30 = 1073741824,当大于这个值时不再扩容。
    2. 如果可以预先知道存储元素的数量,最好在初始化HashMap的时候指定初始容量,这样就可以避免扩容带来的性能消耗。
    3. Java8对HashMap做了优化,增加了红黑树,如果hash碰撞较多时,其搜索性能明显优于链表。

    参考资料:

    Importnew:http://www.importnew.com/20386.html

    博客园:http://www.cnblogs.com/chenssy/p/3521565.html

  • 相关阅读:
    堆栈的链表方式实现
    堆栈的公式化描述实现
    队列的链表方式实现
    队列的实现:公式化描述
    二叉树实现:公式化描述
    算法学习笔记(四):合并排序
    编译caffe报错:_ZN5boost16exception_detail10bad_alloc_D2Ev
    druid的安装
    Error : Must specify a primary resource (JAR or python or R file)
    zip和zippartition总结
  • 原文地址:https://www.cnblogs.com/jenkinschan/p/7726928.html
Copyright © 2011-2022 走看看