zoukankan      html  css  js  c++  java
  • HashMap探究

    HashMap

    前置
    //初始化容量
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; 
    //容器最大容量
    static final int MAXIMUM_CAPACITY = 1 << 30;
    //负载因子,在0.75的时候扩大。比如16的时候,12扩大    12/16=0.75
    static final float DEFAULT_LOAD_FACTOR = 0.75f;
    //Node超过8时,转换为红黑树。
    //查找由链表的O(n)转换为O(log(n)) 对数级
    static final int TREEIFY_THRESHOLD = 8;
    
    

    Node

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

    数组:

     transient Node<K,V>[] table;
    
    put操作
     final V putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict) {
            Node<K,V>[] tab; Node<K,V> p; int n, i;
            //为空则初始化Node[]数组
            if ((tab = table) == null || (n = tab.length) == 0)
                n = (tab = resize()).length;
            //判读数组位置是否有Node占据,如果没有,直接复制
            if ((p = tab[i = (n - 1) & hash]) == null)
                tab[i] = newNode(hash, key, value, null);
            //数据已占据,采取链表
            else {
                Node<K,V> e; K k;
                //hash和key相等,则更新值就可以了
                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 {
                    //p相当于数组坐标的位置
                    //把数据插入链表
                    for (int binCount = 0; ; ++binCount) {
                        if ((e = p.next) == null) {
                            p.next = newNode(hash, key, value, null);
                            //如果大于TREEIFY_THRESHOLD即是大于等于7,说明链表长度为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;
                    }
                }
                if (e != null) { // existing mapping for key
                    V oldValue = e.value;
                    if (!onlyIfAbsent || oldValue == null)
                        e.value = value;
                    afterNodeAccess(e);
                    return oldValue;
                }
            }
            //修改次数
            ++modCount;
             //数组到底用了多少个格子
            //threshold记录的是当前数组格子用了多少,超出大小*负载因子则需要扩容
            if (++size > threshold)
                resize();
            afterNodeInsertion(evict);
            return null;
        }
    
    get操作
        public V get(Object key) {
            Node<K,V> e;
            return (e = getNode(hash(key), key)) == null ? null : e.value;
        }
    

    hash操作

        static final int hash(Object key) {
            int h;
            return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
        }
    
    resize
     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
            }
            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) {
                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;
        }
    

    问题要点

    数据结构:链表+数组

    // 链表
    node{
        object key
        object value
        Node next
    }
    //数组
    elemDate[]
    

    hash函数实现

        static final int hash(Object key) {
            int h;
            //低16位和高16位异或,右移后异或,保证hash分散,降低重复率。防止数组后面的链表过长,尽可能用齐数组
            return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
        } 
    
        public native int hashCode();
    

    检查是否hash碰撞

      if ((p = tab[i = (n - 1) & hash]) == null)
                tab[i] = newNode(hash, key, value, null);
    

    成员变量:threshold 记录数组用了多少。易混static final int TREEIFY_THRESHOLD = 8; 为链表转红黑树的大小。

            //数组到底用了多少个格子
            ++modCount;
            if (++size > threshold)
                resize();
            afterNodeInsertion(evict);
            return null;
    
            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;
    

    resize()方法:Initializes or doubles table size 初始化或者双倍扩容 以双倍扩容 (n-1)&hash与也可以体现出来

    ////雨露均沾,链表上的值,分配到新的数组上
    if (e.next == null)
                            newTab[e.hash & (newCap - 1)] = e;
    
                               if ((e.hash & oldCap) == 0) {
                                    if (loTail == null)
                                        loHead = e;
                                    else
                                        loTail.next = e;
                                    loTail = e;
                                }
    

    HashMap回顾

    1. HashMap的原理,内部结构?

      底层使用哈希表(数组+链表),当链表过长时会将链表转换为红黑树以实现O(logn)时间复杂度内的查找。

    2. 将一下HashMap中put方法的过程

      1. 对key求hash值,然后再计算下标
      2. 如果没有碰撞,直接放入桶中
      3. 如果碰撞了,以链表的形式链接再后面
      4. 如果链表长度超过阈值,就会把链表转为红黑树
      5. 如果节点已经存在就替换旧值
      6. 如果桶满了(容量*负载因子),就需要resize
    3. HashMap中的hash函数时怎么实现的?还有那些hash的实现方式

      1. 高16bit不变,低16bit和高16bit做异或
      2. (n-1)& hash 得到下标
      3. 有哪些Hash的实现方式
    4. HashMap怎么解决冲突,将一下扩容机制,假如一个值在原数组中,现在移动了新数组,位置肯定改变了,那是什么定位到这个新数组中的位置。

      1. 将新节点加到链表后
      2. 容量扩充为原来的两倍,然后对每个节点重新计算哈希值
      3. 这个值只可能在两个地方,一个时原下标位置,另一种是下标为<原下标+原容量>的位置
    5. 抛开HashMap,hash冲突有哪些解决方法

      1. 开放地址发
      2. 链地址发
    6. 针对HashMap中某个Entry链太长,查找时间复杂度可能达到O(n),怎么优化?

      1. 将链表转换为红黑树
  • 相关阅读:
    ajax提交请求返回对象异常问题
    Rhino+envjs-1.2.js 在java运行网站js 工具类
    CryptoJS遇到的小坑
    BT是如何下载的
    NPOI 复制Word中的表格内容, 操作Word表格
    使用Scapy框架进行PPPOE拨号密码截取
    用Python养一只DHT爬虫
    如何解决jquery版本冲突
    安装ECMall后报PHP Strict Standards错误,请问如何解决
    如何在Webstorm/Phpstorm中设置连接FTP,并快速进行文件比较,上传下载,同步等操作(远程开发)
  • 原文地址:https://www.cnblogs.com/renqiqiang/p/9452679.html
Copyright © 2011-2022 走看看