HashMap

前置
  1. //初始化容量
  2. static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;
  3. //容器最大容量
  4. static final int MAXIMUM_CAPACITY = 1 << 30;
  5. //负载因子,在0.75的时候扩大。比如16的时候,12扩大 12/16=0.75
  6. static final float DEFAULT_LOAD_FACTOR = 0.75f;
  7. //Node超过8时,转换为红黑树。
  8. //查找由链表的O(n)转换为O(log(n)) 对数级
  9. static final int TREEIFY_THRESHOLD = 8;

Node

  1. static class Node<K,V> implements Map.Entry<K,V> {
  2. final int hash;
  3. final K key;
  4. V value;
  5. Node<K,V> next;
  6. Node(int hash, K key, V value, Node<K,V> next) {
  7. this.hash = hash;
  8. this.key = key;
  9. this.value = value;
  10. this.next = next;
  11. }

数组:

  1. transient Node<K,V>[] table;
put操作
  1. final V putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict) {
  2. Node<K,V>[] tab; Node<K,V> p; int n, i;
  3. //为空则初始化Node[]数组
  4. if ((tab = table) == null || (n = tab.length) == 0)
  5. n = (tab = resize()).length;
  6. //判读数组位置是否有Node占据,如果没有,直接复制
  7. if ((p = tab[i = (n - 1) & hash]) == null)
  8. tab[i] = newNode(hash, key, value, null);
  9. //数据已占据,采取链表
  10. else {
  11. Node<K,V> e; K k;
  12. //hash和key相等,则更新值就可以了
  13. if (p.hash == hash &&
  14. ((k = p.key) == key || (key != null && key.equals(k))))
  15. e = p;
  16. else if (p instanceof TreeNode)
  17. e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
  18. else {
  19. //p相当于数组坐标的位置
  20. //把数据插入链表
  21. for (int binCount = 0; ; ++binCount) {
  22. if ((e = p.next) == null) {
  23. p.next = newNode(hash, key, value, null);
  24. //如果大于TREEIFY_THRESHOLD即是大于等于7,说明链表长度为8了,做转换操作
  25. if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
  26. treeifyBin(tab, hash);
  27. break;
  28. }
  29. //判断hash和key是否相等,如果相等,则进行更新操作
  30. if (e.hash == hash &&
  31. ((k = e.key) == key || (key != null && key.equals(k))))
  32. break;
  33. p = e;
  34. }
  35. }
  36. if (e != null) { // existing mapping for key
  37. V oldValue = e.value;
  38. if (!onlyIfAbsent || oldValue == null)
  39. e.value = value;
  40. afterNodeAccess(e);
  41. return oldValue;
  42. }
  43. }
  44. //修改次数
  45. ++modCount;
  46. //数组到底用了多少个格子
  47. //threshold记录的是当前数组格子用了多少,超出大小*负载因子则需要扩容
  48. if (++size > threshold)
  49. resize();
  50. afterNodeInsertion(evict);
  51. return null;
  52. }
get操作
  1. public V get(Object key) {
  2. Node<K,V> e;
  3. return (e = getNode(hash(key), key)) == null ? null : e.value;
  4. }

hash操作

  1. static final int hash(Object key) {
  2. int h;
  3. return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
  4. }
resize
  1. final Node<K,V>[] resize() {
  2. Node<K,V>[] oldTab = table;
  3. int oldCap = (oldTab == null) ? 0 : oldTab.length;
  4. int oldThr = threshold;
  5. int newCap, newThr = 0;
  6. if (oldCap > 0) {
  7. if (oldCap >= MAXIMUM_CAPACITY) {
  8. threshold = Integer.MAX_VALUE;
  9. return oldTab;
  10. }
  11. //扩容数组,位移效率更高
  12. else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
  13. oldCap >= DEFAULT_INITIAL_CAPACITY)
  14. newThr = oldThr << 1; // double threshold
  15. }
  16. else if (oldThr > 0) // initial capacity was placed in threshold
  17. newCap = oldThr;
  18. else { // zero initial threshold signifies using defaults
  19. newCap = DEFAULT_INITIAL_CAPACITY;
  20. newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
  21. }
  22. if (newThr == 0) {
  23. float ft = (float)newCap * loadFactor;
  24. newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
  25. (int)ft : Integer.MAX_VALUE);
  26. }
  27. threshold = newThr;
  28. @SuppressWarnings({"rawtypes","unchecked"})
  29. //分配内存地址
  30. Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
  31. table = newTab;
  32. //雨露均沾
  33. if (oldTab != null) {
  34. for (int j = 0; j < oldCap; ++j) {
  35. Node<K,V> e;
  36. //如果数组位置有值
  37. if ((e = oldTab[j]) != null) {
  38. oldTab[j] = null;
  39. //数组下有链表进入
  40. if (e.next == null)
  41. newTab[e.hash & (newCap - 1)] = e;
  42. //是二叉树,进行二叉树的拆分方式
  43. else if (e instanceof TreeNode)
  44. ((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
  45. //链表的拆分方式
  46. else { // preserve order
  47. Node<K,V> loHead = null, loTail = null;
  48. Node<K,V> hiHead = null, hiTail = null;
  49. Node<K,V> next;
  50. do {
  51. next = e.next;
  52. if ((e.hash & oldCap) == 0) {
  53. if (loTail == null)
  54. loHead = e;
  55. else
  56. loTail.next = e;
  57. loTail = e;
  58. }
  59. else {
  60. if (hiTail == null)
  61. hiHead = e;
  62. else
  63. hiTail.next = e;
  64. hiTail = e;
  65. }
  66. //很体现循环遍历的地方
  67. } while ((e = next) != null);
  68. if (loTail != null) {
  69. loTail.next = null;
  70. newTab[j] = loHead;
  71. }
  72. if (hiTail != null) {
  73. hiTail.next = null;
  74. newTab[j + oldCap] = hiHead;
  75. }
  76. }
  77. }
  78. }
  79. }
  80. return newTab;
  81. }

问题要点

数据结构:链表+数组

  1. // 链表
  2. node{
  3. object key
  4. object value
  5. Node next
  6. }
  7. //数组
  8. elemDate[]

hash函数实现

  1. static final int hash(Object key) {
  2. int h;
  3. //低16位和高16位异或,右移后异或,保证hash分散,降低重复率。防止数组后面的链表过长,尽可能用齐数组
  4. return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
  5. }
  6. public native int hashCode();

检查是否hash碰撞

  1. if ((p = tab[i = (n - 1) & hash]) == null)
  2. tab[i] = newNode(hash, key, value, null);

成员变量:threshold 记录数组用了多少。易混static final int TREEIFY_THRESHOLD = 8; 为链表转红黑树的大小。

  1. //数组到底用了多少个格子
  2. ++modCount;
  3. if (++size > threshold)
  4. resize();
  5. afterNodeInsertion(evict);
  6. return null;
  1. newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
  2. }
  3. if (newThr == 0) {
  4. float ft = (float)newCap * loadFactor;
  5. newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
  6. (int)ft : Integer.MAX_VALUE);
  7. }
  8. threshold = newThr;

resize()方法:Initializes or doubles table size 初始化或者双倍扩容 以双倍扩容 (n-1)&hash与也可以体现出来

  1. ////雨露均沾,链表上的值,分配到新的数组上
  2. if (e.next == null)
  3. newTab[e.hash & (newCap - 1)] = e;
  1. if ((e.hash & oldCap) == 0) {
  2. if (loTail == null)
  3. loHead = e;
  4. else
  5. loTail.next = e;
  6. loTail = e;
  7. }

HashMap回顾

  1. HashMap的原理,内部结构?

    底层使用哈希表(数组+链表),当链表过长时会将链表转换为红黑树以实现O(logn)时间复杂度内的查找。

  2. 将一下HashMap中put方法的过程

    1. 对key求hash值,然后再计算下标
    2. 如果没有碰撞,直接放入桶中
    3. 如果碰撞了,以链表的形式链接再后面
    4. 如果链表长度超过阈值,就会把链表转为红黑树
    5. 如果节点已经存在就替换旧值
    6. 如果桶满了(容量*负载因子),就需要resize
  3. HashMap中的hash函数时怎么实现的?还有那些hash的实现方式

    1. 高16bit不变,低16bit和高16bit做异或
    2. (n-1)& hash 得到下标
    3. 有哪些Hash的实现方式
  4. HashMap怎么解决冲突,将一下扩容机制,假如一个值在原数组中,现在移动了新数组,位置肯定改变了,那是什么定位到这个新数组中的位置。

    1. 将新节点加到链表后
    2. 容量扩充为原来的两倍,然后对每个节点重新计算哈希值
    3. 这个值只可能在两个地方,一个时原下标位置,另一种是下标为<原下标+原容量>的位置
  5. 抛开HashMap,hash冲突有哪些解决方法

    1. 开放地址发
    2. 链地址发
  6. 针对HashMap中某个Entry链太长,查找时间复杂度可能达到O(n),怎么优化?

    1. 将链表转换为红黑树

HashMap探究的更多相关文章

  1. HashMap遍历方式探究

    HashMap的遍历有两种常用的方法,那就是使用keyset及entryset来进行遍历,但两者的遍历速度是有差别的,下面请看实例: package com.HashMap.Test; import ...

  2. 【原创】关于hashcode和equals的不同实现对HashMap和HashSet集合类的影响的探究

    这篇文章做了一个很好的测试:http://blog.csdn.net/afgasdg/article/details/6889383,判断往HashSet(不允许元素重复)里塞对象时,是如何判定set ...

  3. HashMap 死循环的探究

    大家都知道,HashMap采用链表解决Hash冲突,具体的HashMap的分析可以参考一下http://zhangshixi.iteye.com/blog/672697 的分析.因为是链表结构,那么就 ...

  4. HashMap原理探究

    一.写随笔的原因:HashMap我们在平时都会用,一般面试题也都会问,借此篇文章分析下HashMap(基于JDK1.8)的源码. 二.具体的内容: 1.简介: HashMap在基于数组+链表来实现的, ...

  5. Java集合系列[3]----HashMap源码分析

    前面我们已经分析了ArrayList和LinkedList这两个集合,我们知道ArrayList是基于数组实现的,LinkedList是基于链表实现的.它们各自有自己的优劣势,例如ArrayList在 ...

  6. java finally深入探究

    When---什么时候需要finally: 在jdk1.7之前,所有涉及到I/O的相关操作,我们都会用到finally,以保证流在最后的正常关闭.jdk1.7之后,虽然所有实现Closable接口的流 ...

  7. SpringCloud学习之DiscoveryClient探究

    当我们使用@DiscoveryClient注解的时候,会不会有如下疑问:它为什么会进行注册服务的操作,它不是应该用作服务发现的吗?下面我们就来深入的来探究一下其源码. 一.Springframewor ...

  8. 细说java系列之HashMap原理

    目录 类图 源码解读 总结 类图 在正式分析HashMap实现原理之前,先来看看其类图. 源码解读 下面集合HashMap的put(K key, V value)方法探究其实现原理. // 在Hash ...

  9. 探究ElasticSearch中的线程池实现

    探究ElasticSearch中的线程池实现 ElasticSearch里面各种操作都是基于线程池+回调实现的,所以这篇文章记录一下java.util.concurrent涉及线程池实现和Elasti ...

随机推荐

  1. 深入理解苹果系统(Unicode)字符串的排序方法

    欢迎大家前往腾讯云+社区,获取更多腾讯海量技术实践干货哦~ 本文由iminder发表于云+社区专栏 Unicode编码 我们知道计算机是不能直接处理文本的,而是和数字打交道.因此,为了表示文本,就建立 ...

  2. shiro教程2(自定义Realm)

    通过shiro教程1我们发现仅仅将数据源信息定义在ini文件中与我们实际开发环境有很大不兼容,所以我们希望能够自定义Realm. 自定义Realm的实现 创建自定义Realmjava类 创建一个jav ...

  3. JAVA中ArrayList与LinkedList的区别以及对应List使用foreach与使用下标遍历的效率问题

    近期在做一个对接京东的电商平台,所以对各个地方的效率考虑的比较多,今天深挖了一下ArrayList与LinkedList的区别以及对应List使用foreach与使用下标遍历的效率问题,首先说一下两种 ...

  4. .net Framework 源代码 · ScrollViewer

    本文是分析 .net Framework 源代码的系列,主要告诉大家微软做 ScrollViewer 的思路,分析很简单 看完本文,可以学会如何写一个 ScrollViewer ,如何定义一个 ISc ...

  5. SQLServer 2008R2 清理日志文件

    设置数据库为简单模式 2.收缩日志文件 3.恢复数据库为完整模式

  6. 初学HTML-8

    video标签:播放视频 格式一:<video src=""> </video> video标签的属性: src:用于告诉video标签需要播放的视频地址. ...

  7. js 动态绑定事件 on click 完美解决绑定不成功

    动态绑定坑了多少人..... //绑定   $("ol").on("click","li a",function(){ ...   }) / ...

  8. 1788:Pell数列

    1788:Pell数列 查看 提交 统计 提问 总时间限制:  3000ms 内存限制:  65536kB 描述 Pell数列a1, a2, a3, ...的定义是这样的,a1 = 1, a2 = 2 ...

  9. [简记] github 上的 GraphQL v4 API

    突发奇想,想用github做一个支持rss的blog体系,或者就是知识管理体系,简单看了下,把测试用的暂存起来 # Type queries into this side of the screen, ...

  10. Hadoop shell命令

    1.FS Shell 调用文件系统(FS)shell命令应使用bin/hadoop fs <args>的形式.所有的的FS shell命令使用URI路径作为参数.URI格式是scheme: ...