美文网首页
散列表实现原理

散列表实现原理

作者: Noblel | 来源:发表于2017-12-30 00:10 被阅读0次

    散列表:

    1. 用hash函数将查找的键转换成数组索引

    • 正整数

    除留余数法:对任意正数k,计算k除以M的余数。java中为(K % M)

    • 浮点数

    将键转换成二进制然后使用除留余数法

    • 字符串

      String中实现:

        for (int i = 0; i < value.length; i++) {
            h = 31 * h + val[i];
        }
      

      公式:

        s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
      
    • 自定义

    希望hashCode()方法能够将键平均的散布为所有可能的32位正数,String,Integer,Double,File对象的hashCode都可以,我们可以将对象的每个变量的hashCode返回值转换为32位正数,并且计算得到散列值。

        private final String who;
        private final Date when;
        private final double amount;
    
        public int hashCode() {
            int hash = 17;
            hash = 31 * hash + who.hashCode();
            hash = 31 * hash + when.hashCode();
            hash = 31 * hash + ((Double) amount).hashCode();
            return hash;
        }
    
    • 软缓存

    如果计算很耗时间,我们可以将每个键的散列值缓存起来,使用一个hash变量来保存hashCode返回值

    2. 解决碰撞

    • 拉链法(链地址法)

    将大小为M的数组中每个元素指向一条链表,链表的每个结点都存储散列值为该元素的索引的键值对

    实现:

    1. 使用原始的链表数据类型
    2. 为M个元素构建符号表来保存散列的键
    • 线性探测法(开放地址法)

    散列值被占用冲突时,直接检查下一个位置(索引加1)

    1. 命中,该位置的键和被查找的键相同
    2. 未命中,键为空(该位置没有键),直接返回
    3. 继续查找,该位置的键和被查找的键不同
    线性探测法.png

    Java中的HashMap

    先开看下Node有什么?

    //实现了Map.Entry接口
    static class Node<K,V> implements Map.Entry<K,V> {
        //存了一个hash值,用来定位数组的位置
        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() {
            //返回(key的hash值 异或 value的hash值)
            return Objects.hashCode(key) ^ Objects.hashCode(value);
        }
    
        public final V setValue(V newValue) {
            V oldValue = value;
            value = newValue;
            return oldValue;
        }
    
        /**
         * 判断是否equals
         */
        public final boolean equals(Object o) {
            if (o == this)
                return true;
            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;
        }
    }
    

    哦,就是一个键值对,能指向下一个地方的键值对

    当我们用map.put("noblel","android");系统会调用putVal(hash(key), key, value, false, true)方法到下面这个方法,先看下hash(key)方法

    对于任意对象,只要hashCode返回值相同,那么调用hash(key)的返回值总是相同,我们需要进行模运算使元素分布相对来说比较均匀。做这一步主要是解决碰撞,如果是直接进行运算,(n-1)& h 只有低位有效很容易产生碰撞。所以先高16位和低16位异或下。

    static final int hash(Object key) {
        int h;
        //先获取hashCode值,然后h ^ h >>>16,得到一个32位的值,还需要取模运算去确定在数组中的位置
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }
    
    
    /**
     * 1.对key的hashCode做hash运算,计算出在表中的位置
     * 2.如果没有碰撞直接方法坑中
     * 3.如果碰撞了就以链表的方式放在桶后面
     * 4.链表过长那就转成红黑树
     * 5.如果桶满了就重新resize
     * 6.节点存在就替换保证唯一性
     */
    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)
            //重新计算大小
            n = (tab = resize()).length;
        //table为空就创建
        if ((p = tab[i = (n - 1) & hash]) == null)
            //这一步就是定位,很巧妙,看分析1
            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);
                        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;
        //超过load factor*current capacity,resize
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }
    
    
    public V get(Object key) {
        Node<K,V> e;
        return (e = getNode(hash(key), key)) == null ? null : e.value;
    }
    
    /**
     * 1.桶中第一个节点直接命中
     * 2.有冲突,通过equals去查找对应节点
     */
    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;
    }
    
    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;
            }
            //没有超过就扩充为原来的2倍
            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) {
                    //先把原位置的桶置为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;
                            //分析2
                            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);
                        //原节点放到新表的原位置中,比如原来是5,现在还是5
                        if (loTail != null) {
                            loTail.next = null;
                            newTab[j] = loHead;
                        }
                        //原索引放到新表【原位置+原表大小】位置中,并且下一个节点置为null,比如原来是9,表大小为16,现在就是25
                        if (hiTail != null) {
                            hiTail.next = null;
                            newTab[j + oldCap] = hiHead;
                        }
                    }
                }
            }
        }
        return newTab;
    }
    

    分析1:

    n:表的大小

    由于直接%的运算比较大,所以HashMap中调用了这个方法(n- 1) & hash 这种效率更高

    hashCode: 1111 1111 1101 1111 1111 1100 1101 1010

    h>>>16: 0000 0000 0000 0000 1111 1111 1101 1111

    hash(hashCode ^ h>>>16) : 1111 1111 1101 1111 0000 0011 0000 0101

    (n- 1) & hash 等同于 hash % n

    n默认是16 0000 0000 0000 0000 0000 0000 0001 0000

    hash: 1111 1111 1101 1111 0000 0011 0000 0101 --->4292805381

    n-1: 0000 0000 0000 0000 0000 0000 0000 1111 --->15

    (n- 1) & hash: 0000 0000 0000 0000 0000 0000 0000 0101 --->5

    4292805381 / 16 = 268300336余5

    分析2:
    e:原表中的每个桶
    oldCap: 原表桶的个数,实际就是分析1中的n
    e.hash & oldCap == 0
    判断这个节点是否的hash值新加的bit是0还是1,什么意思呢?分析1中的确定位置是使用n-1和hash按位与的,但是我们这里相当于直接使用了n 和 hash按位与,位置相同hashCode不一定相同,比如17 / 2 余1, 19 / 2 也是余1,但是他们的hashCode不一样的,所以16扩容到32后,看二进制的后五位,所以有部分会在原位置,有些会到后面n的位置。

    相关文章

      网友评论

          本文标题:散列表实现原理

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