首页 > 其他 > 详细

HashMap、ConcurrentHashMap数据结构、底层原理、源码分析

时间:2020-04-11 17:23:55      阅读:63      评论:0      收藏:0      [点我收藏+]
  • HashMap

 

数据结构

JDK1.7 

HashMap由数组+链表组成,数组是HashMap的主体,链表则是主要为了解决哈希冲突而存在的。

技术分享图片

 

JDK1.8

HashMap由数组+链表/红黑树组成,当链表长度大于阈值(默认为8)时,将链表转化为红黑树,以减少搜索时间。

技术分享图片

转为红黑树后,链表的结构仍然会存在,通过next属性维持,红黑树节点在进行操作时都会维护链表的结构

底层原理

 怎么实现存取?

  • put

 

/**
 * JDK 1.7
 */
public V put(K key, V value) {
    if (table == EMPTY_TABLE) {
        inflateTable(threshold);
    }
    if (key == null)
        return putForNullKey(value);
    int hash = hash(key);
    int i = indexFor(hash, table.length);
    for (Entry<K,V> e = table[i]; e != null; e = e.next) {
        Object k;
        if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
            V oldValue = e.value;
            e.value = value;
            e.recordAccess(this);
            return oldValue;
        }
    }

    modCount++;
    addEntry(hash, key, value, i);
    return null;
}

/** nullkey */
private V putForNullKey(V value) {
    for (Entry<K,V> e = table[0]; e != null; e = e.next) {
        if (e.key == null) {
            V oldValue = e.value;
            e.value = value;
            e.recordAccess(this);
            return oldValue;
        }
    }
    modCount++;
    addEntry(0, null, value, 0);
    return null;
}

 

  • get

 

/**
 * JDK 1.7
 */
public V get(Object key) {
    if (key == null)
        return getForNullKey();
    Entry<K,V> entry = getEntry(key);

    return null == entry ? null : entry.getValue();
}

final Entry<K,V> getEntry(Object key) {
    if (size == 0) {
        return null;
    }

    int hash = (key == null) ? 0 : hash(key);
    for (Entry<K,V> e = table[indexFor(hash, table.length)];
         e != null;
         e = e.next) {
        Object k;
        if (e.hash == hash &&
            ((k = e.key) == key || (key != null && key.equals(k))))
            return e;
    }
    return null;
}

private V getForNullKey() {
    if (size == 0) {
        return null;
    }
    for (Entry<K,V> e = table[0]; e != null; e = e.next) {
        if (e.key == null)
            return e.value;
    }
    return null;
}

 

源码分析

 

  • ConcurrentHashMap

 

数据结构

 

底层原理

 

源码分析

技术分享图片

 

HashMap、ConcurrentHashMap数据结构、底层原理、源码分析

原文:https://www.cnblogs.com/scorpio-cat/p/12680487.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!