广告
返回顶部
首页 > 资讯 > 后端开发 > Python >JavaHashMap源码深入分析讲解
  • 860
分享到

JavaHashMap源码深入分析讲解

2024-04-02 19:04:59 860人浏览 薄情痞子

Python 官方文档:入门教程 => 点击学习

摘要

1.HashMap是数组+链表(红黑树)的数据结构。 数组用来存放HashMap的Key,链表、红黑树用来存放HashMap的value。 2.HashMap大小的确定: 1) Ha

1.HashMap数组+链表(红黑树)的数据结构

数组用来存放HashMap的Key,链表、红黑树用来存放HashMap的value。

2.HashMap大小的确定:

1) HashMap的初始大小是16,在下面的源码分析中会看到。

2)如果创建时给定大小,HashMap会通过计算得到1、2、4、8、16、32、64....这样的二进制位作为HashMap数组的大小。

    //如何做到的呢?通过右移和或运算,最终n = xxx11111。n+1 = xx100000,2的n次方,即为数组大小
    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 + 1;
    }

3.如何将key映射成数组角标:

我们都知道数组的下标是0,1,2,3,4,5,6.....这样的连续整数,那么、HashMap是怎么将Key转换成对应的数组角标的呢?

	//1. int h = key.hashCode 得到key的hashCode.
    //2. int j = h>>>16 右移16位
    //3. int hash = h^j 异或,将hashCode变为hash值。
    //通过hash算法将hashCode转换为hash值,注意hash值和hashCode不是一回事。
    //4.int index = (n - 1) & hash,n是数组的长度,计算得到的index即为数组的角标。
	//有兴趣的朋友,可以写几行代码进行验证。
    static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }
	static final int index(int hash,int n){
		return (n - 1) & hash;
	}

4.Value值如何存储?

HashMap将key的hashCode转换为数组角标,必然会存在多个元素的key转换成同一个角标的情况。针对这样的情况,HashMap采用链表和红黑数的方式存储Value值。java8以后默认先以单链表的方式存储。当单链表中的元素超过8个后,单链表会转换成红黑树数据结构。当红黑树上的节点数量少于6个会重新变为单链表结构。

5.put实现原理:

1)通过算法,计算出key对应的数组角标。

2)取出数组角标存储的节点,如果为null直接存储,如果不为null,则对链表进行遍历,先比较两个元素的hash值,再判断key的equale,如果一样,说明key已经存在,则不存储,这也就是hashmapKey不能重复的原因。如果不一样,则以链表或红黑树的方式存储。

final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
        node<K,V>[] tab; Node<K,V> p; int n, i;
        //如果数组是null 或者长度为0,则创建数组 resize()
        if ((tab = table) == null || (n = tab.length) == 0)
            //resize既是创建,也是扩容
            n = (tab = resize()).length;
        //取出索引为i的Node赋值给p,如果为null,说明这个位置没有节点
        if ((p = tab[i = (n - 1) & hash]) == null)
            //创建Node,并放在角标为i的位置。这个node是一个单链表结构
            tab[i] = newNode(hash, key, value, null);
        else {//如果i的位置有节点,则添加到链表中
            Node<K,V> e; K k;
            //先判断hash是否一致,再判断key,如果一样,则说明是同一个Key,
            //直接将p赋值给e,这也就是hashMap和HashSet的key不能重复的原因
            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 {
                //创建新的node添加的链表的末尾
                for (int binCount = 0; ; ++binCount) {
                    //将下一个节点赋值给e。如果e==null,说明遍历到最后一个节点,
                    if ((e = p.next) == null) {
                        //创建新的节点,添加到链表末尾
                        p.next = newNode(hash, key, value, null);
                        //static final int TREEIFY_THRESHOLD = 8;
                        //当链表长度大于等于8时,
                        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;
                    //将当前的e赋值给p
                    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;
    }

6.get方法,HashMap如何取出元素。

取数据时,如何判断传入的key和map中的key是同一个key呢?

e.hash == hash &&

((k = e.key) == key || (key != null && key.equals(k)))

通过源码可以看到,必须满足两个条件,hash值必须相等,然后再判断,key的引用是否一致,或者key的equals是否是true。这也就是为啥要同时复写对象的hashCode和equals方法的原因。

public V get(Object key) {
        Node<K,V> e;
        return (e = getNode(hash(key), key)) == null ? null : e.value;
    }
    final Node<K,V> getNode(int hash, Object key) {
        Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
        // 数组不为空且长度大于0,对应角标的第一个node,first
        if ((tab = table) != null && (n = tab.length) > 0 &&
                (first = tab[(n - 1) & hash]) != null) {
            if (first.hash == hash && //如果和第一个是同一个直接返回
                    ((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);//遍历链表取出和key一致的node
            }
        }
        return null;
    }

7.HashMap的扩容

扩容因子: static final float DEFAULT_LOAD_FACTOR = 0.75f;

默认大小:static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16

扩容阈值:int threshold;

 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) {//数组长度大于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; // 数组大于默认大小时, 扩容阈值是原来的2倍
            }
        } else if (oldThr > 0) //初始化时,threshold已被设置(调用有参构造函数时)
            newCap = oldThr; //将数组长度设置为threshold值。
        else { //如果数组和阈值都为0 (调用无参构造函数)
            newCap = DEFAULT_INITIAL_CAPACITY; //默认数组大小,
            //扩容阈值为默认数组大小的0.75倍
            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;
    }
}

到此这篇关于Java HashMap源码深入分析讲解的文章就介绍到这了,更多相关Java HashMap内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

本文标题: JavaHashMap源码深入分析讲解

本文链接: https://www.lsjlt.com/news/166145.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作