简单聊聊HashMap

[TOC]

1 HashMap为什么线程不安全?

对于大部分公司来说:java8已经能够满足业务需求,同时以稳定性为主,不轻易升级版本。

/**
     * Associates the specified value with the specified key in this map.
     * If the map previously contained a mapping for the key, the old
     * value is replaced.
     *
     * @param key key with which the specified value is to be associated
     * @param value value to be associated with the specified key
     * @return the previous value associated with {@code key}, or
     *         {@code null} if there was no mapping for {@code key}.
     *         (A {@code null} return can also indicate that the map
     *         previously associated {@code null} with {@code key}.)
     */
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;
        if ((p = tab[i = (n - 1) & hash]) == null)
            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;
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }

底层实现:数组加链表

首先通过hashcode()函数计算出hash值,然后取余得到下标,当hash冲突的时候1.7采用的是头插法,头插法速度快一些,不需要遍历到尾节点,这时候get的时候就不能取得头插法的元素,因为你的头结点是周瑜,所以这里就必须每次插入之后移动链表

分析源码:首先看构造方法,无参,指定数组容量,总的属性16*0.75=12;

public static int highestOneBit(int i) {
        return i & (MIN_VALUE >>> numberOfLeadingZeros(i));
    }

public static int numberOfLeadingZeros(int i) {
        // HD, Count leading 0's
        if (i <= 0)
            return i == 0 ? 32 : 0;
        int n = 31;
        if (i >= 1 << 16) { n -= 16; i >>>= 16; }
        if (i >= 1 <<  8) { n -=  8; i >>>=  8; }
        if (i >= 1 <<  4) { n -=  4; i >>>=  4; }
        if (i >= 1 <<  2) { n -=  2; i >>>=  2; }
        return n - (i >>> 1);
    }
8421
先翻译成二进制数,有一个位数为一,其他都不为一
0000 0101  代表10
put和get环环相扣的,必须是2的N次幂,才能通过-1加上与运算得到小于length的下标,配套使用
不管高四位怎么变,最终的结果的都不会变,但是int类型很多不一样,所以就会有冲突,影响get的元素,遍历比较慢
右移且进行了异或运算的原因,提高返回来的hashcode的散列性,

扩容的目的就是提高搜索效率

长链表变成短链表

头插法1,2,3扩容之后变成3,2,1

单线程的会怎么样?扩容resize()两个线程都会newTable公用

调用Put的时候,多线程扩容的时候会导致循环链表,因为可以会阻塞

记得先看构造函数,看各种方法,一层层往里面挖

记得看注释说明

熟悉数据结构与算法看源码会简单很多

代码量膨胀了一倍来解决这些问题

数组+链表/红黑树

扩容时插入顺序的改进

函数方法 forEach compute系列
Map新的API merge replace

java 7 中经典的哈希表实现

存在的问题:非常容易碰到死锁,潜在的安全隐患

Computes key.hashCode() and spreads (XORs) higher bits of hash
* to lower.  Because the table uses power-of-two masking, sets of
* hashes that vary only in bits above the current mask will
* always collide. (Among known examples are sets of Float keys
* holding consecutive whole numbers in small tables.)  So we
* apply a transform that spreads the impact of higher bits
* downward. There is a tradeoff between speed, utility, and
* quality of bit-spreading. Because many common sets of hashes
* are already reasonably distributed (so don't benefit from
* spreading), and because we use trees to handle large sets of
* collisions in bins, we just XOR some shifted bits in the
* cheapest possible way to reduce systematic lossage, as well as
* to incorporate impact of the highest bits that would otherwise
* never be used in index calculations because of table bounds.
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;
    }

扩充HashMap的时候,不需要计算hash,只需要看原来的hash值新增的bit是1还是0,是0的话索引不变,是1的话变成“原索引+旧容量”,正是这样巧妙地rehash方式,即省去了重新计算hash值的时间,而且同时,由于新增的1bit是0还是1可以认为是随机的,均匀地分散冲突的节点到新的桶中

全部评论

相关推荐

coffrar:全都是已读😅沟通一千五百多个了
点赞 评论 收藏
分享
new和malloc的区别?c++里new了数组怎么释放?32位系统的指针变量占多大字节?int*呢?空类呢?c++多态?为什么需要虚析构?虚析构实现原理?c++可以不写构造函数吗?编译器默认除了构造还会有什么?深拷贝和浅拷贝区别?智能指针哪个c++版本引入的,作用?用过哪些容器?项目里用了哪些容器?为什么用qlist?qmap什么是key?模板的好处?什么时候会用?设计模式了解哪些?自己写过吗?单例模式怎么写?单例要返回非静态指针类型怎么弄?队列和栈的区别?osi七层以及相应协议?网络层的协议?应用层?一些项目问题...网络加密算法知道哪些?tcp的三次握手四次挥手回收写过吗?写服务器基本模...
AI牛可乐:哇,你分享了好多面试经验呢,听起来你准备得很充分呢!👍 关于你提到的技术问题,我来帮你解答一下吧: 1. `new` 和 `malloc` 的区别?`new` 会自动调用构造函数,而 `malloc` 只负责分配内存。`new` 数组释放时用 `delete[]`,比如 `delete[] myArray;`。 2. 在32位系统中,指针变量通常占4个字节,`int*` 也是如此。 3. 空类的实例通常占1个字节,但具体实现可能不同。 4. C++多态允许我们通过基类指针或引用来调用派生类的函数。需要虚析构是因为基类指针可能指向派生类对象,不使用虚析构可能导致派生类析构函数不被调用。 5. 如果不写构造函数,编译器会提供一个默认构造函数。默认构造函数会进行成员变量的默认初始化。 6. 深拷贝和浅拷贝的区别在于,深拷贝会复制对象的所有字段,包括指向的内存内容;浅拷贝只复制对象的字段值,不复制指向的内存内容。 7. 智能指针是在C++11版本引入的,用于自动管理内存,防止内存泄漏。 8. 常用的容器有 `vector`、`list`、`map` 等。具体使用哪个容器取决于项目需求。 关于你问的其他问题,我简单回答一下: - `QList` 通常用于需要频繁插入和删除的场景。 - `QMap` 的 `key` 是映射表中的键值。 - 模板的好处是提高代码复用性,减少代码冗余。 - 设计模式有很多种,比如单例模式、工厂模式等。单例模式可以通过静态成员函数实现。 现在,悄悄告诉你一个小秘密,点击我的头像,我们可以私信聊天哦~🎉 那么,你平时在项目中都用过哪些容器呢?有没有什么特别的经验或者技巧可以分享的呢?😊
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务