hashmap源码分析( 基于java8)

hashmap源码分析

简介

hashmap的get和put操作的时间复杂度是常量。通过调用哈希函数将元素正确的分布到桶中。初始容量(capacity)的值不能设置太高,加载因子(loadfactor)不能设置的太低,否则会影响迭代的性能。
一个hashmap的实例有两个参数将影响它的性能。初始容量、加载因子。初始容量是hashmap在创建时候桶的大小。加载因子用来确定何时进行扩容(size > 容量*加载因子)。扩容的时候也会进行对内部的数据结构进行重新构建,使桶的大小增加两倍。

默认的加载因子(0.75)在时间和空间复杂度上提供了很好的权衡。大一点的话会减少空间但是会增加get和put的时间。

hashmap可以存键值为null,是线程不安全的。如果想线程安全可以使用Collections.synchronizedMap()包装.
或者使用ConcurrentMap,这个map是线程安全的。

hashmap数据结构

hashmap是一个散列表,存储的内容是key-value。就像我们用的字典一样,用过字母(key)查找单词(value)。hashmap的时间复杂度是O(longN)。

在java8之前hashmap采用的是+链表的数据结构。但是如果数据很大,链表的查找时间复杂度是O(n),显然者违背了hashmap的初衷,所以在链表的元素大于8的时候,java8会把链表旋转为红黑树

《hashmap源码分析( 基于java8)》

[数组 链表 散列(hash)
](https://blog.csdn.net/u013565…

hashmap的数据结构实现

桶,链表的实现

桶的实现:

transient Node<K,V>[] table;

链表的实现:

    
    
static class Node<K,V> implements Map.Entry<K,V> {

    final int hash;//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;
}
}

重要属性

static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // 默认的桶初始容量(2^4=16)。

static final int MAXIMUM_CAPACITY = 1 << 30;//最大的桶的容量

static final float DEFAULT_LOAD_FACTOR = 0.75f;//默认的加载因子

static final int TREEIFY_THRESHOLD = 8;//当链表大于这个阈值会被旋转为红黑树

static final int UNTREEIFY_THRESHOLD = 6;//当做resize操作的时候,如果桶中某个节点的数量小于这个阈值,则把树旋转为链表

static final int MIN_TREEIFY_CAPACITY = 64;//当桶中的数量大于64是,才会判断是否转换成树

transient Node<K,V>[] table;//桶

transient int size;//hashmap的存储的元素大小

transient int modCount;//hashmap结构被修改的次数

int threshold;//扩容阈值

final float loadFactor;//加载因子

构造方法

构造方法会创建一个空的桶,计算扩容阈值和加载因子

HashMap(int,float)

public HashMap(int initialCapacity, float loadFactor) {//桶初始化容量,加载因子
if (initialCapacity < 0)//桶初始容量不能小于0
    throw new IllegalArgumentException("Illegal initial capacity: " +
                                       initialCapacity);
if (initialCapacity > MAXIMUM_CAPACITY)//如果桶初始化容量大于hashmap最大的容量,则初始化容量等于最大的容量
    initialCapacity = MAXIMUM_CAPACITY;
if (loadFactor <= 0 || Float.isNaN(loadFactor))//
    throw new IllegalArgumentException("Illegal load factor: " +
                                       loadFactor);
this.loadFactor = loadFactor;
this.threshold = tableSizeFor(initialCapacity);//计算扩容阈值
}

HashMap(int)

public HashMap(int initialCapacity) {
this(initialCapacity, DEFAULT_LOAD_FACTOR);//加载因子为默认的0.75
}

HashMap()

public HashMap() {
        this.loadFactor = DEFAULT_LOAD_FACTOR; //桶初始容量为0,加载因为0.75
}

HashMap(Map)

public HashMap(Map<? extends K, ? extends V> m) {
this.loadFactor = DEFAULT_LOAD_FACTOR;//加载因子为默认的0.75
putMapEntries(m, false);//map放入桶中
}



final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) {
int s = m.size();//插入元素大小
if (s > 0) {//如果大于0 ,则继续进行插入操作
    if (table == null) { // pre-size
        float ft = ((float)s / loadFactor) + 1.0F;
        int t = ((ft < (float)MAXIMUM_CAPACITY) ?
                 (int)ft : MAXIMUM_CAPACITY);
        if (t > threshold)
            threshold = tableSizeFor(t);
    }
    else if (s > threshold)//如果插入元素数量大于扩容阈值,则桶的大小扩容两倍
        resize();
    for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) {
        K key = e.getKey();
        V value = e.getValue();
        putVal(hash(key), key, value, false, evict);//插入元素
    }
}
}

主要的几个方法分析

get(Obejct)

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


//根据key获取value
final Node<K,V> getNode(int hash, Object key) {
Node<K,V>[] tab; Node<K,V> first, e; int n; K k;//tab:桶 first:桶中节点的第一个元素    n:桶的长度 k:第一个节点的key
if ((tab = table) != null && (n = tab.length) > 0 &&
    (first = tab[(n - 1) & hash]) != null) {//如果桶不为空,并且key所在的节点的第一个元素不为空
    if (first.hash == hash && // always check first node
        ((k = first.key) == key || (key != null && key.equals(k))))//如果key是节点的第一元素则返回节点的第一个元素
        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;
}

put(K,V)

public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}


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);//如果key所在的桶第一个元素为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)//如果hashmap中的元素等于扩容阈值,则重新构造数据结构
    resize();
afterNodeInsertion(evict);
return null;
}

hash()

static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}

h是原始的hash返回的值是int类型,int取值范围:-2147483648到2147483648,前后加起来大概四十亿的映射空间。只要hash函数映射的比较松散,一般是很难出现碰撞的。
但是考虑到实际的内存的大小,很难放下这么大的数组。

所以为了空间上的考虑上述中的扰动函数,对原始计算出来的hash值(int 四个字节32位),右移16位,自己的高半区和低半区做异或,就是为了混合原始hash值的高位和地位,以此来加大低位的随机性。而且混合后的地位参杂了高位的部分特征,这样高位的信息也被变相的保留下来了。

线程安全性

hashmap线程不安全的,如果要使用安全的hashmap建议使用ConcurrentHashMap。

参考:

hash()原理: https://www.zhihu.com/questio…

关注我的公众号第一时间阅读有趣的技术故事
扫码关注:
《hashmap源码分析( 基于java8)》
也可以在微信搜索公众号即可关注我:codexiulian
渴望与你一起成长进步!

    原文作者:HashMap源码分析
    原文地址: https://segmentfault.com/a/1190000016201033
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞