了解HashMap原理之前先了解一下几种数据结构:

1、数组:采用一段连续的内存空间来存储数据。对于指定下标的查找,时间复杂度为O(1),对于给定元素的查找,需要遍历整个数据,时间复杂度为O(n)。但对于有序

  数组的查找,可用二分查找法,时间复杂度为O(logn),对于一般的插入删除操作,涉及到数组元素的移动,其平均时间复杂度为O(n)。

2、哈希表:也叫散列表,用的是数组支持元素下标随机访问的特性,将键值映射为数组的下标进行元素的查找。所以哈希表就是数组的一种扩展,将键值映射为元素下标的函数叫做

  哈希函数,哈希函数运算得到的结果叫做哈希值。哈希函数的设计至关重要,好的哈希函数会尽可能地保证计算简单和散列地址分布均匀。

  哈希冲突(也叫哈希碰撞):不同的键值通过哈希函数运算得到相同的哈希值,解决哈希冲突的方式有开放寻址法和链表法,ThreadLocalMap由于其元素个数较少,

  采用的是开放寻址法,而HashMap采用的是链表法来解决哈希冲突,即所有散列值相同的元素都放在相同槽对应的链表中(也就是数组+链表的方式)

3、链表:链表使用内存中不连续的内存块进行数组的存储,其不支持随机访问,每次元素的查找都要遍历整个链表,时间复杂度为O(n)。

  HashMap是由数组+链表构成的,即存放链表的数组,数组是HashMap的主体,链表则是为了解决哈希碰撞而存在的,如果定位到的数组不包含链表(当前的entry指向为null),那么对于查找,删除等操作,时间复杂度仅为O(1),如果定位到的数组包含链表,对于添加操作,其时间复杂度为O(n),首先需要遍历链表,存在相同的key则覆盖value,否则新增;对于查找操作,也是一样需要遍历整个链表,然后通过key对象的equals方法逐一比对,时间复杂度也为O(n)。所以,HashMap中链表出现的越少,长度越短,性能才越好,这也是HashMap设置阀值即扩容的原因。

HashMap的主干是一个Entry数组,Entry是HashMap的基本组成单元,每一个Entry包含一个key-value键值对。

  1. /**
  2. * An empty table instance to share when the table is not inflated.
  3. */
  4. static final Entry<?,?>[] EMPTY_TABLE = {};
  5. /**
  6. * The table, resized as necessary. Length MUST Always be a power of two.
  7. */
  8. transient Entry<K,V>[] table = (Entry<K,V>[]) EMPTY_TABLE;

Entry是HashMap中的一个静态内部类

  1. static class Entry<K,V> implements Map.Entry<K,V> {
  2. final K key;
  3. V value;
  4. Entry<K,V> next;
  5. int hash;
  6.  
  7. /**
  8. * Creates new entry.
  9. */
  10. Entry(int h, K k, V v, Entry<K,V> n) {
  11. value = v;
  12. next = n;
  13. key = k;
  14. hash = h;
  15. }
  16.  
  17. public final K getKey() {
  18. return key;
  19. }
  20.  
  21. public final V getValue() {
  22. return value;
  23. }
  24.  
  25. public final V setValue(V newValue) {
  26. V oldValue = value;
  27. value = newValue;
  28. return oldValue;
  29. }
  30.  
  31. public final boolean equals(Object o) {
  32. if (!(o instanceof Map.Entry))
  33. return false;
  34. Map.Entry e = (Map.Entry)o;
  35. Object k1 = getKey();
  36. Object k2 = e.getKey();
  37. if (k1 == k2 || (k1 != null && k1.equals(k2))) {
  38. Object v1 = getValue();
  39. Object v2 = e.getValue();
  40. if (v1 == v2 || (v1 != null && v1.equals(v2)))
  41. return true;
  42. }
  43. return false;
  44. }
  45.  
  46. public final int hashCode() {
  47. return Objects.hashCode(getKey()) ^ Objects.hashCode(getValue());
  48. }
  49.  
  50. public final String toString() {
  51. return getKey() + "=" + getValue();
  52. }
  53.  
  54. /**
  55. * This method is invoked whenever the value in an entry is
  56. * overwritten by an invocation of put(k,v) for a key k that's already
  57. * in the HashMap.
  58. */
  59. void recordAccess(HashMap<K,V> m) {
  60. }
  61.  
  62. /**
  63. * This method is invoked whenever the entry is
  64. * removed from the table.
  65. */
  66. void recordRemoval(HashMap<K,V> m) {
  67. }
  68. }

其他属性:

  1. /**
  2. * The default initial capacity - MUST be a power of two.处理容量,2的4次方,16,扩容后的容量必须是2的次方
  3. */
  4. static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
  5.  
  6. /**
  7. * The maximum capacity, used if a higher value is implicitly specified
  8. * by either of the constructors with arguments.
  9. * MUST be a power of two <= 1<<30.  最大容量,2的30次方
  10. */
  11. static final int MAXIMUM_CAPACITY = 1 << 30;
  12.  
  13. /**
  14. * The load factor used when none specified in constructor.  默认负载因子,0.75f
  15. */
  16. static final float DEFAULT_LOAD_FACTOR = 0.75f;
  17. /**
  18. * The next size value at which to resize (capacity * load factor).
  19. * @serial
  20. */
  21. // If table == EMPTY_TABLE then this is the initial capacity at which the
  22. // table will be created when inflated.
  23. int threshold;  扩容阀值

构造函数:

  1. public HashMap(int initialCapacity, float loadFactor) {
         // 校验初始容量值是否合法
  2. if (initialCapacity < 0)
  3. throw new IllegalArgumentException("Illegal initial capacity: " +
  4. initialCapacity);
  5. if (initialCapacity > MAXIMUM_CAPACITY)
  6. initialCapacity = MAXIMUM_CAPACITY;
  7. if (loadFactor <= 0 || Float.isNaN(loadFactor))
  8. throw new IllegalArgumentException("Illegal load factor: " +
  9. loadFactor);
  10.     
  11. this.loadFactor = loadFactor;
         // 目前扩容阀值等于初始容量,在真正构建数组的时候,其值为 容量*负载因子
  12. threshold = initialCapacity;
  13. init();
  14. }

可以看到,在进行put操作的时候才真正构建table数组

put方法:

  1. public V put(K key, V value) {
  2. if (table == EMPTY_TABLE) {
  3. inflateTable(threshold);
  4. }
  5. if (key == null)
  6. return putForNullKey(value);
         // 根据key计算哈希值
  7. int hash = hash(key);
         // 根据哈希值和数据长度计算数据下标
  8. int i = indexFor(hash, table.length);
  9. for (Entry<K,V> e = table[i]; e != null; e = e.next) {
  10. Object k;
           // 哈希值相同再比较key是否相同,相同的话值替换,否则将这个槽转成链表
  11. if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
  12. V oldValue = e.value;
  13. e.value = value;
  14. e.recordAccess(this);
  15. return oldValue;
  16. }
  17. }
  18.  
  19. modCount++;  // fast-fail,迭代时响应快速失败,还未添加元素就进行modCount++,将为后续留下很多隐患
  20. addEntry(hash, key, value, i);  // 添加元素,注意最后一个参数i是table数组的下标
  21. return null;
  22. }

inflateTable:

  1. /**
  2. * Inflates the table.
  3. */
  4. private void inflateTable(int toSize) {
  5. // Find a power of 2 >= toSize,寻找大于等于toSize的最小的2的次幂,如果toSize=13,则capacity=16;toSize=16,capacity=16
         // toSize=28,capacity=32;也就是说,当你设置了HashMap的初始容量initCapacity时,并不是存储的数据达到设置的初始容量initCapacity*loadFactor时就扩容
         // 而是到了capacity = roundUpToPowerOf2(initCapacity),capacity *loadFactor时才会扩容。
  6. int capacity = roundUpToPowerOf2(toSize); // 返回小于(toSize- 1) *2的最接近的2的次幂 ,如果toSize=1,则capacity=1,所以如果将initcapacity设为的话,第一次put不会扩容
  7.  
  8. threshold = (int) Math.min(capacity * loadFactor, MAXIMUM_CAPACITY + 1);
  9. table = new Entry[capacity];
  10. initHashSeedAsNeeded(capacity);
  11. }

hash方法:

  1. final int hash(Object k) {
  2. int h = hashSeed;
  3. if (0 != h && k instanceof String) {
  4. return sun.misc.Hashing.stringHash32((String) k);
  5. }
  6.     // 先取key的hashCode再和hashSeed进行异或运算
  7. h ^= k.hashCode();
  8.  
  9. // This function ensures that hashCodes that differ only by
  10. // constant multiples at each bit position have a bounded
  11. // number of collisions (approximately 8 at default load factor).
  12. h ^= (h >>> 20) ^ (h >>> 12);
  13. return h ^ (h >>> 7) ^ (h >>> 4);
  14. }

indexFor:

  1. /**
  2. * Returns index for hash code h.  返回数组下标
  3. */
  4. static int indexFor(int h, int length) {
  5. // assert Integer.bitCount(length) == 1 : "length must be a non-zero power of 2";
  6. return h & (length-1);  保证获取的index一定在数组范围内
  7. }

所以最终存储位置的获取流程是这样的:

key--hashCode()-->hashCode--hash()-->h--indexFor()、h&(length-1)-->存储下标

addEntry:

  1.    transient int size;  // Entry数组实际大小
  2. void addEntry(int hash, K key, V value, int bucketIndex) {
         // 添加新元素前先判断数组的大小是否大于等于阀值,如果是且数组下标位置已经存在元素则对数组进行扩容,并对新的key重新根据新的数组长度计算下标
  3. if ((size >= threshold) && (null != table[bucketIndex])) {
           // 数组长度扩容为之前的2倍
  4. resize(2 * table.length);
  5. hash = (null != key) ? hash(key) : 0;
  6. bucketIndex = indexFor(hash, table.length);
  7. }
  8.     
  9. createEntry(hash, key, value, bucketIndex);
  10. }
      // 将新的key-value存入Entry数组并size自增1
  11. void createEntry(int hash, K key, V value, int bucketIndex) {
  12. Entry<K,V> e = table[bucketIndex];  //如果两个线程同时执行到此处,那么一个线程的赋值就会被另一个覆盖掉,这是对象丢失的原因之一
  13. table[bucketIndex] = new Entry<>(hash, key, value, e);  
  14. size++;
  15. }

resize:

  1. void resize(int newCapacity) {
         // 保存就的数组
  2. Entry[] oldTable = table;
  3. int oldCapacity = oldTable.length;
         // 判断数组的长度是不是已经达到了最大值
  4. if (oldCapacity == MAXIMUM_CAPACITY) {
  5. threshold = Integer.MAX_VALUE;
  6. return;
  7. }
  8.      // 创建一个新的数组
  9. Entry[] newTable = new Entry[newCapacity];
         // 将旧数组的内容转换到新的数组中
  10. transfer(newTable, initHashSeedAsNeeded(newCapacity));
  11. table = newTable;
         // 计算新数组的扩容阀值
  12. threshold = (int)Math.min(newCapacity * loadFactor, MAXIMUM_CAPACITY + 1);
  13. }

transfer:

哈希桶内的元素被逆序排列到新表中

  1. /**
  2. * Transfers all entries from current table to newTable.
  3. */
  4. void transfer(Entry[] newTable, boolean rehash) {
  5. int newCapacity = newTable.length;
         // 遍历旧数组得到每一个key再根据新数组的长度重新计算下标存进去,如果是一个链表,则链表中的每个键值对也都要重新hash计算索引
  6. for (Entry<K,V> e : table) {
          // 如果此slot上存在元素,则进行遍历,直到e==null,退出循环
  7. while(null != e) {
  8. Entry<K,V> next = e.next;
             // 当前元素总是直接放在数组下标的slot上,而不是放在链表的最后,所以
  9. if (rehash) {
  10. e.hash = null == e.key ? 0 : hash(e.key);
  11. }
  12. int i = indexFor(e.hash, newCapacity);
             // 把原来slot上的元素作为当前元素的下一个
  13. e.next = newTable[i];
             // 新迁移过来的节点直接放置在slot位置上
  14. newTable[i] = e;
  15. e = next;
  16. }
  17. }
  18. }

get方法:

  1. public V get(Object key) {
        // 如果key为null,直接去table[0]处去检索即可
  2. if (key == null)
  3. return getForNullKey();
  4. Entry<K,V> entry = getEntry(key); // 根据key去获取Entry数组
  5.  
  6. return null == entry ? null : entry.getValue();
  7. }
  8. final Entry<K,V> getEntry(Object key) {
  9. if (size == 0) {
  10. return null;
  11. }
  12.      // 根据key的hashCode重新计算hash值
  13. int hash = (key == null) ? 0 : hash(key);
         // 获取查找的key所在数组中的索引,然后遍历链表,通过equals方法对比key找到对应的记录
  14. for (Entry<K,V> e = table[indexFor(hash, table.length)];
  15. e != null;
  16. e = e.next) {
  17. Object k;
  18. if (e.hash == hash &&
  19. ((k = e.key) == key || (key != null && key.equals(k))))
  20. return e;
  21. }
  22. return null;
  23. }

get方法相对比较简单,key(hashCode)-->hash-->indexFor-->index,找到对应位置table[index],再查看是否有链表,通过key的equals方法对比找到对应的记录。

重写equal方法的同时必须重写hashCode()方法?如果不重写会有什么问题呢?

如:User类重写了equals方法却没有重写hashCode方法

  1. public class User {
  2. private int age;
  3. private String name;
  4.  
  5. public User(int age, String name) {
  6. this.age = age;
  7. this.name = name;
  8. }
  9.  
  10. public int getAge() {
  11. return age;
  12. }
  13.  
  14. public void setAge(int age) {
  15. this.age = age;
  16. }
  17.  
  18. public String getName() {
  19. return name;
  20. }
  21.  
  22. public void setName(String name) {
  23. this.name = name;
  24. }
  25.  
  26. @Override
  27. public boolean equals(Object o) {
  28. if (this == o) {
  29. return true;
  30. }
  31. if (o == null || getClass() != o.getClass()) {
  32. return false;
  33. }
  34. User user = (User) o;
  35. return age == user.age &&
  36. Objects.equals(name, user.name);
  37. }
  38.  
  39. }

将其作为key存入HashMap中,然后获取

  1. User user = new User(20, "yangyongjie");
  2. Map<User, String> map = new HashMap<>(1);
  3. map.put(user, "菜鸟");
  4. String value = map.get(new User(20, "yangyongjie"));
  5. System.out.println(value); //null

结果却为null,为什么呢?因为在默认情况下,hashCode方法是将对象的存储地址进行映射的,Object.hashCode()的实现是默认为每一个对象生成不同的int数值,它本身是native方法,一般与对象内存地址相关。而上面put和get的User虽然通过重写了equals方法使其逻辑上年龄和姓名相等的两个对象被判定为同一个对象,但是其两个对象的地址值并不相同,因此hashCode一定不同,那自然在put时的下标和get时的下标也不同。所以,如果重写了equals方法一定要同时重写hashCode方法。

此外,因为Set存储的是不重复的对象,依据hashCode和equals进行判断,所以Set存储的自定义对象也必须重写这两个方法。

补充一下:未重写前的equals方法和hashCode方法都可以用来比较两个对象的地址值是否相同,不同的是,两个地址值不同的对象的hashCode可能相同,但是equals一定不同。

HashMap存在的一些问题

死链:

  两个线程A,B同时对HashMap进行resize()操作,在执行transfer方法的while循环时,若此时当前槽上的元素为a-->b-->null

  1、线程A执行到 Entry<K,V> next = e.next;时发生阻塞,此时e=a,next=b

  2、线程B完整的执行了整段代码,此时新表newTable元素为b-->a-->null

  3、线程A继续执行后面的代码,执行完一个循环之后,newTable变为了a<-->b,造成while(e!=null) 一直死循环,CPU飙升

扩容数据丢失:

  同样在resize的transfer方法上

  1、当前线程迁移过程中,其他线程新增的元素有可能落在已经遍历过的哈希槽上;在遍历完成之后,table数组引用指向了newTable,

    这时新增的元素就会丢失,被无情的垃圾回收。

  2、如果多个线程同时执行resize,每个线程又都会new Entry[newCapacity],此时这是线程内的局部变量,线程之前是不可见的。迁移完成

    后,resize的线程会给table线程共享变量,从而覆盖其他线程的操作,因此在被覆盖的new table上插入的数据会被丢弃掉。

JDK1.7 hashMap源码分析的更多相关文章

  1. JDK1.8 HashMap源码分析

      一.HashMap概述 在JDK1.8之前,HashMap采用数组+链表实现,即使用链表处理冲突,同一hash值的节点都存储在一个链表里.但是当位于一个桶中的元素较多,即hash值相等的元素较多时 ...

  2. JDK1.8 HashMap 源码分析

    一.概述 以键值对的形式存储,是基于Map接口的实现,可以接收null的键值,不保证有序(比如插入顺序),存储着Entry(hash, key, value, next)对象. 二.示例 public ...

  3. JDK1.7 HashMap 源码分析

    概述 HashMap是Java里基本的存储Key.Value的一个数据类型,了解它的内部实现,可以帮我们编写出更高效的Java代码. 本文主要分析JDK1.7中HashMap实现,JDK1.8中的Ha ...

  4. jdk1.8 HashMap源码分析(resize函数)

    // 扩容兼初始化 final Node<K, V>[] resize() { Node<K, V>[] oldTab = table; int oldCap = (oldTa ...

  5. HashMap源码分析(一)

    基于JDK1.7 HashMap源码分析 概述 HashMap是存放键值对的集合,数据结构如下: table被称为桶,大小(capacity)始终为2的幂,当发生扩容时,map容量扩大为两倍 Hash ...

  6. HashMap 源码分析 基于jdk1.8分析

    HashMap 源码分析  基于jdk1.8分析 1:数据结构: transient Node<K,V>[] table;  //这里维护了一个 Node的数组结构: 下面看看Node的数 ...

  7. HashMap实现原理(jdk1.7),源码分析

    HashMap实现原理(jdk1.7),源码分析 ​ HashMap是一个用来存储Key-Value键值对的集合,每一个键值对都是一个Entry对象,这些Entry被以某种方式分散在一个数组中,这个数 ...

  8. 源码分析系列1:HashMap源码分析(基于JDK1.8)

    1.HashMap的底层实现图示 如上图所示: HashMap底层是由  数组+(链表)+(红黑树) 组成,每个存储在HashMap中的键值对都存放在一个Node节点之中,其中包含了Key-Value ...

  9. 【JAVA集合】HashMap源码分析(转载)

    原文出处:http://www.cnblogs.com/chenpi/p/5280304.html 以下内容基于jdk1.7.0_79源码: 什么是HashMap 基于哈希表的一个Map接口实现,存储 ...

随机推荐

  1. r_action

    皮尔逊相关系数 斯皮尔曼等级相关(Spearman Rank Correlation) http://wiki.mbalib.com/wiki/斯皮尔曼等级相关 从表中的数字可以看出,工人的考试成绩愈 ...

  2. 术语-BLOB:BLOB

    ylbtech-术语-Blob:Blob 计算机视觉中的Blob是指图像中的一块连通区域,Blob分析就是对前景/背景分离后的二值图像,进行连通域提取和标记.标记完成的每一个Blob都代表一个前景目标 ...

  3. python tensorflow windows环境搭建体验

    1. 需先安装python3.7,anaconda包管理器(类似java的maven),tensorflow,pycharm开发工具.文末附件下载地址. 2. 安装tensorflow,开始-Anac ...

  4. 【ABAP系列】SAP ABAP 工单增强

    公众号:SAP Technical 本文作者:matinal 原文出处:http://www.cnblogs.com/SAPmatinal/ 原文链接:[ABAP系列]SAP ABAP 工单增强   ...

  5. Neo4j elk Elasticsearch kibana kettle

    图形数据库,用于查找犯罪或者啥的很好用:反欺诈 win安装neo4j使用查询https://www.cnblogs.com/rubinorth/p/5853204.html linux下安装neo4j ...

  6. Ubuntu12.04安装MariaDB并修改字符集为UTF-8

    其实按照MariaDB官网的步骤来安装MariaDB特别的简单,只要按照步骤来做,很容易就搞定了. 首先,到MariaDB官网: https://downloads.mariadb.org/maria ...

  7. 洛谷 P1731 [NOI1999]生日蛋糕(搜索剪枝)

    题目链接 https://www.luogu.org/problemnew/show/P1731 解题思路 既然看不出什么特殊的算法,显然是搜索... dfs(u,v,s,r0,h0)分别表示: u为 ...

  8. 牛客练习赛27-----C.水图(DFS求最长路径)

    传送门 来源:牛客网题目描述:小w不会离散数学,所以她van的图论游戏是送分的小w有一张n个点n-1条边的无向联通图,每个点编号为1~n,每条边都有一个长度小w现在在点x上她想知道从点x出发经过每个点 ...

  9. IEnumerable和IEnumerator 详解 分类: C# 2014-12-05 11:47 18人阅读 评论(0) 收藏

    原:<div class="article_title"> <span class="ico ico_type_Original">&l ...

  10. k3 cloud成本调整单提示期末余额不存在调整单分录的维度,请先出库核算确认是否存在核算维度的数据

    成本调整单提示期末余额不存在调整单分录的维度,请先出库核算确认是否存在核算维度的数据,如下图所示: 解决办法:先做出库核算,然后做成本调整单,再做出库核算(出库成本核算)