HashMap初步面试题

1、HashMap的数据结构与底层原理

1、HashMap在1.7的时候用的是数组加链表,1.8之后是数组加链表加红黑树。
2、数组里面存了一个是key-value的键值对,在1.7的时候叫Entry,1.8叫Node
3、key和value可以为空

2、put过程(1.8)

1、根据key生成hashcode 2、判断当前HashMap对象中的数组是否为空,如果为空则初始化该数组
3、1.7的时候会进行4次无符号右移,5个与运算,1.8会进行高16位和低16位进行逻辑与运算,算出hashcode基于当前数组对应的数组下标i
4.判断数组的第i个位置的元素(tab[i])是否为空
a. 如果为空,则将key,value封装为Node对象赋值给tab[i]
b. 如果不为空:
i. 如果put⽅法传⼊进来的key等于tab[i].key,那么证明存在相同的key
ii. 如果不等于tab[i].key,则:
1. 如果tab[i]的类型是TreeNode,则表示数组的第i位置上是⼀颗红⿊树,那么将key和value插⼊到红⿊树中,并且在插⼊之前会判断在红⿊树中是否存在相同的key
2. 如果tab[i]的类型不是TreeNode,则表示数组的第i位置上是⼀个链表,那么遍历链表寻找是否存在相同的key,并且在遍历的过程中会对链表中的结点数进⾏计数,当遍历到最后⼀个结点时,会将key,value封装为Node插⼊到链表的尾部,同时判断在插⼊新结点之前的链表结点个数是不是⼤于等于8,且数组的长度大于64,如果是,则将链表改为红⿊树。
iii. 如果上述步骤中发现存在相同的key,则根据onlyIfAbsent标记来判断是否需要更新value值,然后返回oldValue
5. modCount++
6. HashMap的元素个数size加1
7. 如果size⼤于扩容的阈值,则进⾏扩容

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

    public final K getKey()        { return key; }
    public final V getValue()      { return value; }
    public final String toString() { return key + "=" + value; }

    public final int hashCode() {
        return Objects.hashCode(key) ^ Objects.hashCode(value);
    }

    public final V setValue(V newValue) {
        V oldValue = value;
        value = newValue;
        return oldValue;
    }

    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;
    }
}
//put的过程
public V put(K key, V value) {
    return putVal(hash(key), key, value, false, true);
}
//1.7的hash
  final int hash(Object k) {
        int h = 0;
        if (useAltHashing) {
            if (k instanceof String) {
                return sun.misc.Hashing.stringHash32((String) k);
            }
            h = hashSeed;
        }

        h ^= k.hashCode();
        h ^= (h >>> 20) ^ (h >>> 12);
        return h ^ (h >>> 7) ^ (h >>> 4);
}
//1.8的hash
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)
        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;
}

3、get过程

  1. 根据key⽣成hashcode
  2. 如果数组为空,则直接返回空
  3. 如果数组不为空,则利⽤hashcode和数组⻓度通过逻辑与操作算出key所对应的数组下标i
  4. 如果数组的第i个位置上没有元素,则直接返回空
  5. 如果数组的第1个位上的元素的key等于get⽅法所传进来的key,则返回该元素,并获取该元素的value
  6. 如果不等于则判断该元素还有没有下⼀个元素,如果没有,返回空
  7. 如果有则判断该元素的类型是链表结点还是红⿊树结点 a. 如果是链表则遍历链表 b. 如果是红⿊树则遍历红⿊树
  8. 找到即返回元素,没找到的则返回空
//get方法
public V get(Object key) {
    Node<K,V> e;
    return (e = getNode(hash(key), key)) == null ? null : e.value;
}
//getNode方法
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;
}

4、JDK8中的HashMap为什么要使⽤红⿊树?

当元素个数⼩于⼀个阈值时,链表整体的插⼊查询效率要⾼于红⿊树,当元素个数⼤于此阈值时,链表整体的插⼊查询效率要低于红⿊树。此阈值在HashMap中为8

5、JDK8中的HashMap什么时候将链表转化为红⿊树?

当发现链表中的元素个数⼤于8之后,还会判断⼀下当前数组的⻓度,如果数组⻓度⼩于64时,此时并不会转化为红⿊树,⽽是进⾏扩容。只有当链表中的元素个数⼤于8,并且数组的⻓度⼤于等于64时才会将链表转为红⿊树。

6、1.7和1.8的不同点

1、1.8用了红黑树
2、1.7插入的时候用了头插法,1.8插入的时候用了尾插法
3、1.7会rehash,1.8没有这份代码逻辑
4、1.8的hash算法时高低16位做异或运算,1.7的时候会进行4次无符号右移,5个与运算==(具体原因:JDK7的Hash算法⽐JDK8中的更复杂,Hash算法越复杂,⽣成的hashcode则更散列,那么hashmap中的元素则更散列,更散列则hashmap的查询性能更好,JDK7中没有红⿊树,所以只能优化Hash算法使得元素更散列,⽽JDK8中增加了红⿊树,查询性能得到了保障,所以可以简化⼀下Hash算法,毕竟Hash算法越复杂就越消耗CPU)==
5. JDK8中扩容的条件和JDK7中不⼀样,除开判断size是否⼤于阈值之外,JDK7中还判断了tab[i]是否为空,不为空的时候才会进⾏扩容,⽽JDK8中则没有该条件了
6. JDK8中还多了⼀个API:putIfAbsent(key,value)
7. JDK7和JDK8扩容过程中转移元素的逻辑不⼀样,JDK7是每次转移⼀个元素,JDK8是先算出来当前位 置上哪些元素在新数组的低位上,哪些在新数组的⾼位上,然后在⼀次性转移

7、1.7和1.8的插入方式

1.7是头插法,1.8是尾插法

8、为什么是尾插

因为1.7是头插法,在多线程情况下会产生循环链表,而1.8改为尾插就不会出现循环链表问题了,还有一点就是链表要转换为红黑树的时候需要用到链表长度

9、扩容机制(resize)

举个例子:当前的容量⼤⼩为16,当你存进第13个的时候,判断发现需要进⾏resize了,也就是插入数据后的容量>=HashMap当前⻓度(6)*负载因子0.75(float
ft = (float)newCap * loadFactor),那就进⾏扩容,具体的就是:
1、创建⼀个新的Entry空数组,⻓度是原数组的2倍。 2、ReHash:遍历原Entry数组,把所有的Entry重新Hash到新数组。

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

10、为什么重新hash(1.7)

因为计算hash的规则改变了(具体看代码) (1.7)Hash的公式—> index = HashCode(Key) & (Length

  • 1)

11、为什么默认容量是16?

采用位运算,是因为位与运算⽐算数计算的效率⾼了很多。之所以选择16,是为了key映射到index的算法

static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16

12、HashMap怎么处理hash碰撞的?

链表法(HashMap),扩展一下还有个开放地址法

13、HashMap线程不安全,那怎么处理?

可以采用HashTable,Collections.synchronizedMap,ConcurrentHashMap,由于前两者的并发度不高,所以线程不安全下都是用ConcurrentHashMap,

我是小白弟弟,一个在互联网行业的小白,立志成为一名架构师
https://blog.csdn.net/zhouhengzhe?t=1

HashMap面试题主要涉及以下几个方面: 1. HashMap的底层数据结构是什么? HashMap的底层数据结构是数组。当进行put()操作时,会进行hash计算,确定对象在数组中的位置。如果多个对象的值在同一个数组位置上,就会出现hash冲突,此时会使用链表来解决冲突。 2. JDK 1.8为什么引入了红黑树? JDK 1.8引入红黑树是为了解决链表过长导致的性能问题。当链表长度超过一定阈值(默认为8),链表会转换为红黑树来提高查找效率。 3. HashMap的内部类Node<K,V>是什么作用? HashMap的内部类Node<K,V>实现了Entry接口,用于存储键值对的数据。每个Node对象表示一个映射关系,包含了键和值。 以上是关于HashMap的一些常见面试题,希望对你有帮助。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [史上最全Hashmap面试总结,51道附带答案,持续更新中...](https://blog.csdn.net/androidstarjack/article/details/124507171)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *2* *3* [【硬核】HashMap最全面试题(附答案)](https://blog.csdn.net/weixin_43689480/article/details/118752906)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

zhz小白

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值