hashMap实现原理分析

哈希表也叫散列表,是一种非常重要的数据结构,许多缓存技术的核心就是在内存中维护一张大的哈希表,应用非常广泛。
hashMap是一个散列表,它存储的内容是键值对映射
hashMap继承于AbstractMap,实现了Map、Cloneable、java.io.Serializable接口
hashMap不是线程安全的,同时也不是有序的

hashMap构造函数
//无参构造方法,构造一个空的hashmap,初始容量为16,负载因子为0.75
hashMap()
//构造一个指定容量大小的hashmap,负载因子为0.75
hashMap(int capacity)
//构造一个指定容量大小,指定负载因子的hashmap
hashMap(int capacity float loadFactor)
//构造一个指定map,容量能充足容下指定的map,负载因子为0.75的hashmap
hashMap(Map<? extends k,? extends v> map)

hashmap扩容

/**
 * The default initial capacity - MUST be a power of two.
 */
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16

hashmap默认容量为1<<4

/**
 * The maximum capacity, used if a higher value is implicitly specified
 * by either of the constructors with arguments.
 * MUST be a power of two <= 1<<30.
 */
static final int MAXIMUM_CAPACITY = 1 << 30;

hashmap最大容量为1<<30

hashmap扩容算法

/**
 * Returns a power of two size for the given target capacity.
 */
static final int tableSizeFor(int cap) {
    int n = cap - 1;
    n |= n >>> 1;
    n |= n >>> 2;
    n |= n >>> 4;
    n |= n >>> 8;
    n |= n >>> 16;
    return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
}

图示如下
在这里插入图片描述
hashmap数据结构
在这里插入图片描述
在这里插入图片描述
hashmap是由数组和链表来实现对数据的存储,数组由一个个桶(bucket)组成,每个桶存储一个或者多个Entry对象,每个Entry对象包含三部分key、value、next。
hashmap实际保存数据是一个由node节点组成的数组。

key取hash值源码

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

key取hash值源码是通过hashCode()的高16位异或低16实现的,这么做可以是table的length小

resize()扩容方法
介绍源码之前,说明下几个变量的含义
loadFactor -负载因子
threshold -阀值,当容易达到此值,table需要扩容操作

final Node<K,V>[] resize() {
    //保存当前table
    Node<K,V>[] oldTab = table;
    //保存当前table的容量
    int oldCap = (oldTab == null) ? 0 : oldTab.length;
    //保存当前阀值
    int oldThr = threshold;
    //初始化新的table容量和阀值
    int newCap, newThr = 0;
    //旧table是否为空
    if (oldCap > 0) {
        //旧table超过table默认最大值,直接赋值位Integer.MAX_VALUE
        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
    }
    //table为空,阀值不为空
    else if (oldThr > 0) // initial capacity was placed in threshold
        //当table没初始化时,threshold持有初始容量
        newCap = oldThr;
    //初始化构造方法调用,两者均小于0
    else {               // zero initial threshold signifies using defaults
        //采用默认赋值
        newCap = DEFAULT_INITIAL_CAPACITY;
        newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
    }
    //新阀值为0,重新赋值新阀值
    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"})
    //初始化table
        Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
    table = newTab;
    if (oldTab != null) {
        //把oldtabe的节点放到newtable上
        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;
}

扩容是计算出所需容器的大小之后重新定义一个新的容器,将原来容器中的元素放入其中

putval()方法源码

final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
               boolean evict) {
    Node<K,V>[] tab; Node<K,V> p; int n, i;
    //table为空直接扩容
    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;
}

hash 冲突发生的几种情况:
1.两节点key 值相同(hash值一定相同),导致冲突;
2.两节点key 值不同,由于 hash 函数的局限性导致hash 值相同,冲突;
3.两节点key 值不同,hash 值不同,但 hash 值对数组长度取模后相同,冲突;

哈希冲突指的是当某个元素通过哈希运算的得到一个存储地址,但是这个存储地址已经被占用了,从而出现冲突。解决哈希冲突的方法用很多种,开放地址法、再散列函数法、链地址法,而hashMap采用的就是链地址法,即数组+链表。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值