美文网首页
Java-HashMap的使用和源码简析

Java-HashMap的使用和源码简析

作者: Allen赵子强 | 来源:发表于2019-02-26 17:11 被阅读0次

    1. 继承关系图谱

    2. 特征

    key-value存储结构,存储的key值无序。key和value可为null

    3. 源码简析(基于jdk1.8)

    HashMap底层的数据结构基于数组和hash函数来实现。先讲一下hash函数,Object类有equals和hashcode两个函数:

    equals函数只有当两个引用指向同一个对象时为true。hashcode函数是native的,所以其实现取决于不同的jvm。上面的一段注释是对jvm实现hashcode函数时的规约,意思是不同的对象应该返回不同的hashcode,由于不同对象的内存地址是不同的,所以可以通过将对象地址作为哈希值来实现。

    equals方法是用来判断两个对象在逻辑上是否相等的,集合类api中的很多操作都需要用到equals,如contains、remove某个对象的操作,都是根据equals去判断。很多时候我们需要覆写equals函数,比如我有一个Book类:

    public class Book {
        
        private String name;
        
        private String author;
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public String getAuthor() {
            return author;
        }
    
        public void setAuthor(String author) {
            this.author = author;
        }
    }
    

    从逻辑上讲,当两个book的名称和作者相同时,认为它们是同一本书,即它们是equals的,这时Book类就需要覆写equals方法:

    public class Book {
    
        private String name;
    
        private String author;
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public String getAuthor() {
            return author;
        }
    
        public void setAuthor(String author) {
            this.author = author;
        }
    
        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;
            Book book = (Book) o;
            return Objects.equal(name, book.name) &&
                    Objects.equal(author, book.author);
        }
    }
    

    hashcode方法就是这个类的hash函数,hash函数就是将某个输入经过特定的规则,映射到某个输出,对于java对象来说,输入就是对象本身,输出是一个int类型的值。

    java规范规定,当一个类覆写了equals函数时,也要覆写hashcode函数。equals和hashcode需要满足,两个对象equals时,它们的hashcode相等,反之不一定成立。如果没有按照规范,覆写equals时没有覆写hashcode,将导致一些依赖hashcode的集合类,如HashMap、Hashtable无法正常工作(原因下面会讲到)。以上面的Book类为例:

    public static void main(String[] args) {
            Map<Book, Integer> map = new HashMap<>();
            Book b1 = new Book();
            b1.setName("a");
            b1.setAuthor("a");
            Book b2 = new Book();
            b2.setName("a");
            b2.setAuthor("a");
            System.out.println(b1.equals(b2));
            map.put(b1, 1);
            System.out.println(map.get(b2));
        }
    

    以上输出:

    true
    null

    此时HashMap没有正常工作,获取已存在的key值的value时返回了null。

    HashMap内部使用Node类数组来存储数据,Node存储key值、value值、经过计算后的key的hash值、以及指向下一个Node的引用。

    HashMap中最核心的就是其put方法,理解了put方法,其他的get、putIfAbsent等方法也自然理解了。

    public V put(K key, V value) {
            return putVal(hash(key), key, value, false, true);
    }
    
    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)
                // 如果table为null,初始化capacity
                n = (tab = resize()).length;
            if ((p = tab[i = (n - 1) & hash]) == null)
                // table数组索引处无Node(p为null),实例化一个Node,放在此索引处
                tab[i] = newNode(hash, key, value, null);
            else {
                // table数组索引处已经有Node(p不为null)
                Node<K,V> e; K k;
                if (p.hash == hash &&
                    ((k = p.key) == key || (key != null && key.equals(k))))
                    // p与要put的key值hash相等且equals(这里先比较hash是因为hash不同也可以映射到数组同一索引,
                    // 但是equals时hash一定是相同的,如果hash不同就不用再进行比较耗时的equals操作)
                    e = p;
                else if (p instanceof TreeNode)
                    // p是TreeNode(即此索引处是红黑树结构)
                    e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
                else {
                    // p是Node(即此索引处是链表结构),遍历链表
                    for (int binCount = 0; ; ++binCount) {
                        if ((e = p.next) == null) {
                            // 遍历完未发现与key相等的,在链表上新增一个Node,保存key和value
                            p.next = newNode(hash, key, value, null);
                            if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                                // 如果链表的长度超过8,将链表转为红黑树结构(还要满足table长度达到64)
                                treeifyBin(tab, hash);
                            break;
                        }
                        if (e.hash == hash &&
                            ((k = e.key) == key || (key != null && key.equals(k))))
                            // 找到与key相等的
                            break;
                        p = e;
                    }
                }
                if (e != null) { // existing mapping for key
                    // 已存在key时,如果onlyIfAbsent为false,则替换原来的value
                    V oldValue = e.value;
                    if (!onlyIfAbsent || oldValue == null)
                        e.value = value;
                    afterNodeAccess(e);
                    return oldValue;
                }
            }
            ++modCount;
            if (++size > threshold)
                // 如果key的数量超过threshold,进行扩容
                resize();
            afterNodeInsertion(evict);
            return null;
    }
    

    之前说过,两个equals的对象其hashcode是相等的,而两个不equals的对象,如果它们的hashcode相等,就称为发生了哈希碰撞。HashMap工作的效率依赖于hashcode函数的设计,一个好的hash函数,应该要尽量减少哈希冲突,并均匀地分散不同的对象。

    来看一下HashMap是怎么利用hashcode获得key在数组中的索引的。首先通过hash方法获得key的hash值,然后将hash值与table数组长度-1相与获得最终的数组索引。举例如下,假设key的hashcode为-3862,hashmap容量为初始的16:

    hashmap的容量总是2的n次幂,所以容量-1其低位都是1,这能保证最后进行按位与操作时,hash值的低位都能对索引值产生影响,尽可能均匀分散key值。由于按位与,而容量-1其高位都是0,这就使得hashcode的高位不对索引产生影响,HashMap在hash方法中将高位与低位异或,使得高位也能对最终的索引产生影响。如何能尽量均匀分散key值,减少冲突是HashMap效率的关键,HashMap在不同jdk版本中的处理也不尽相同,说明其一直在探索更好的方式。

    HashMap在jdk1.8版本中,发生冲突时采用的是链表加红黑树的解决方式,链表结构很好理解,红黑树是TreeMap的底层结构,比较复杂,这边先不展开。

    再来看一下HashMap的扩容方法resize,resize涉及到几个概念,capacity:容量,即Node数组table的长度,其值总为2的n次幂;size:key值的个数;loadFactor:大于0的浮点数,默认值为0.75,表示HashMap的填充系数;threshold:capacity * loadFactor,需要扩容的阀值,当size大于threshold时进行扩容。所以可以看出,loadFactor是决定扩容频繁程度的关键因素,loadFactor越大,扩容越少,但是HashMap越拥挤,查询与插入效率越低;loadFactor越小,扩容越多,HashMap更加疏松,越不容易发生哈希冲突,但占用了更多的空间(数组利用率低)。

    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;
                }
                // new capacity为old capacity的2倍
                else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                         oldCap >= DEFAULT_INITIAL_CAPACITY)
                    // threshold同比扩大2倍
                    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,将Node复制到新的table
                for (int j = 0; j < oldCap; ++j) {
                    Node<K,V> e;
                    if ((e = oldTab[j]) != null) {
                        oldTab[j] = null;
                        if (e.next == null)
                            // 只有一个Node,直接计算新的索引
                            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;
                            // 循环,将原有链表按照&oldCap是否为0,拆成两个链表
                            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);
                            // &oldCap=0的,索引不变
                            if (loTail != null) {
                                loTail.next = null;
                                newTab[j] = loHead;
                            }
                            // &oldCap!=0的,索引为原索引+oldCap
                            if (hiTail != null) {
                                hiTail.next = null;
                                newTab[j + oldCap] = hiHead;
                            }
                        }
                    }
                }
            }
            return newTab;
        }
    

    这边的扩容又用到了capacity为2的n次幂的特点,原来的Node在扩容后,其位置要么不变,要么是原来的索引加上capacity。这么设计使得扩容时不再需要重新计算每个Node的索引(否则每个Node都要重新按put方法的逻辑走一遍),使得扩容变得非常高效。下图直观的解释了扩容后索引的变化:

    理解了put方法,再来看下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) {
                    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;
        }
    

    现在可以解释开头的例子,HashMap查询时先根据hash值定位数组索引,所以如果两个equals的对象hashcode不相同,其定位的索引一般也不同,所以根据相同的key值无法获得value。因此,覆写equals时一定要覆写hashcode,且满足equals为true时hashcode一定相等。

    4. 结论

    HashMap是一个无序map,其底层采用数组+链表+红黑树,查询效率依赖hash函数的设计,最佳条件下查询效率为O(1),如果哈希冲突过多,会用红黑树解决,查询效率为O(logn),因此HashMap的查询十分高效。插入操作在最佳条件下也为O(1),如果插入的地方发生哈希冲突,则效率退化为O(n)或O(logn),总的来说如果散列均匀,插入操作也是很快的。

    相关文章

      网友评论

          本文标题:Java-HashMap的使用和源码简析

          本文链接:https://www.haomeiwen.com/subject/rxczeqtx.html