HashMap深入学习

一、简介
HashMap是哈希表的Map实现,以Key-Value的形式存储数据,根据hash算法,使key-value分布均匀

二、数据结构
HashMap的数据结构在JDK1.7到1.8做了改进,JDK1.7采用数组+链表的结构,JDK1.8在1.7的基础新增了红黑树,即数组+链表+红黑树。之所以加入红黑树的概念,是因为在多次哈希冲突导致链表太长时,自动转换成红黑树,提高查询效率。
JDK17JDK1.8

三、常用方法
HashMap共有4个构造方法:

  HashMap()  //默认构造方法
  HashMap(Map<? extends K, ? extends V> m) //接收一个Map作为参数的构造方法,可以用一个现有的Map初始化一个新的Map
 HashMap(int initialCapacity)//带初始容量的构造方法
 HashMap(int initialCapacity, float loadFactor)//带初始容量和负载因子的构造方法

其他常用方法:

 put(K key, V value)  //将key、value键值对放到HashMap中
 putAll(Map<? extends K, ? extends V> m)//将一个Map中所有元素全部放入此Map中
 get(Object key)//通过key获取对应的value
 remove(Object key)//通过key移除键值对
 containsKey(Object key)//当前Map key的集合中是否含有传入key
 containsValue(Object value)//当前Map value的集合中是否含有传入value
 keySet() //获取key的集合
 size()// Map所含元素个数(包含数组+链接+红黑树中所有的键值对数量)
 isEmpty() //Map是否为空
 resize()//扩容时用到,用来重新整理内部结构
 clear() //清空Map

四、源码分析
1.常用参数

 //默认的初始化容量 16
 static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;
 //最大容量,容量超过会以此容量为准,2的30次方
 static final int MAXIMUM_CAPACITY = 1 << 30;
 //默认的负载因子,跟HashMap的扩容有关
 static final float DEFAULT_LOAD_FACTOR = 0.75f;
 //链表转成红黑树的节点数,当链表节点数达到8个时,会自动转换成红黑树
 static final int TREEIFY_THRESHOLD = 8;
 //红黑树转成链表的节点数,当节点数小于等于6时,自动从红黑树转成链表
 static final int UNTREEIFY_THRESHOLD = 6;
 //表的容量超过此阈值,桶才可以转换成红黑树(数组中的元素称为桶)
 static final int MIN_TREEIFY_CAPACITY = 64;

2.常用方法
这里写图片描述

put将键值对存储到HashMap的基本过程:
1、第一次进行put操作时,调用resize()进行容量的初始化
2、通过hash算法将key映射到数据中的某个元素中
3、如果数组的当前元素中已经存储了数据,此时便产生了hash冲突,需要将已经存储在数组中的数据移到表尾,新put的数据作为表头,放到数组的元素中
4、当hash冲突导致链表的长度达到8,数组中的元素会自动由链接转换成红黑树,提高查询效率

  /**
  * @Param onlyIfAbsent 若为true,不会改变已经存在的value
  **/
  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;//若HashMap为空Map,调用resize()进行初始化容量
    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;//若key在HashMap中已经存在,用新数据将旧数据覆盖掉
      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) {
            //若数组中只存储了一个键值对,没有指向的链表,就新建Node节点
            p.next = newNode(hash, key, value, null);
            //当链表的节点数达到了TREEIFY_THRESHOLD,将链表转换成树
            if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
              treeifyBin(tab, hash);
            break;
          }
          //若存在相同的key,直接覆盖
          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;
        //若onlyIfAbsent为true,当key存在时,不覆盖旧值
        if (!onlyIfAbsent || oldValue == null)
          e.value = value;
        afterNodeAccess(e);
        return oldValue;
      }
    }
    ++modCount;
    if (++size > threshold)
      resize();
    afterNodeInsertion(evict);
    return null;
  }

get方法

public V get(Object key) {
        Node<K,V> e;
        //实际上是传入key与key的hash值,通过getNode来获取key对应的value
        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;
        if ((tab = table) != null && (n = tab.length) > 0 &&
            (first = tab[(n - 1) & hash]) != null) {
            //key与hash都相同,说明映射到的数组位置就是需要返回的元素(没有产生哈希冲突)
            if (first.hash == hash && // always check first node
                ((k = first.key) == key || (key != null && key.equals(k))))
                return first;
            if ((e = first.next) != null) {
                //如果是红黑树,通过getTreeNode方法遍历红黑树得到value
                if (first instanceof TreeNode)
                    return ((TreeNode<K,V>)first).getTreeNode(hash, key);
                do {//遍历链表得到value
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        return e;
                } while ((e = e.next) != null);
            }
        }
        return null;
    }

resize扩容方法

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) {
        //当容量已经达到最大的容量(1<<30)时,不能进行扩容
            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)
                       //若当前Node没有next,说明没有发生哈希冲突,重新根据hash值来计算映射的位置
                        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;
                            //rehash后 节点新的位置一定为原来基础上加上 oldCap
                            newTab[j + oldCap] = hiHead;
                        }
                    }
                }
            }
        }
        return newTab;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值