博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
HashMap实现原理分析
阅读量:4572 次
发布时间:2019-06-08

本文共 6808 字,大约阅读时间需要 22 分钟。

1. HashMap的数据结构

中有数组和链表来实现对数据的存储,但这两者基本上是两个极端。

数组

数组存储区间是连续的,占用内存严重,故空间复杂的很大。但数组的二分查找时间复杂度小,为O(1);数组的特点是:寻址容易,插入和删除困难;

链表

链表存储区间离散,占用内存比较宽松,故空间复杂度很小,但时间复杂度很大,达O(N)。链表的特点是:寻址困难,插入和删除容易。

哈希表

那么我们能不能综合两者的特性,做出一种寻址容易,插入删除也容易的数据结构?答案是肯定的,这就是我们要提起的哈希表。哈希表((Hash table)既满足了数据的查找方便,同时不占用太多的内容空间,使用也十分方便。

哈希表有多种不同的实现方法,我接下来解释的是最常用的一种方法—— 拉链法,我们可以理解为“链表的数组” ,如图:

 

  从上图我们可以发现哈希表是由数组+链表组成的,一个长度为16的数组中,每个元素存储的是一个链表的头结点。那么这些元素是按照什么样的规则存储到数组中呢。一般情况是通过hash(key)%len获得,也就是元素的key的哈希值对数组长度取模得到。比如上述哈希表中,12%16=12,28%16=12,108%16=12,140%16=12。所以12、28、108以及140都存储在数组下标为12的位置。

  HashMap其实也是一个线性的数组实现的,所以可以理解为其存储数据的容器就是一个线性数组。这可能让我们很不解,一个线性的数组怎么实现按键值对来存取数据呢?这里HashMap有做一些处理。

  首先HashMap里面实现一个静态内部类Entry,其重要的属性有 key , value, next,从属性key,value我们就能很明显的看出来Entry就是HashMap键值对实现的一个基础bean,我们上面说到HashMap的基础就是一个线性数组,这个数组就是Entry[],Map里面的内容都保存在Entry[]里面。

/**     * The table, resized as necessary. Length MUST Always be a power of two.     */    transient Entry[] table;

 

2. HashMap的存取实现

     既然是线性数组,为什么能随机存取?这里HashMap用了一个小,大致是这样实现:

1 // 存储时:2 int hash = key.hashCode(); // 这个hashCode方法这里不详述,只要理解每个key的hash是一个固定的int值3 int index = hash % Entry[].length;4 Entry[index] = value;5 6 // 取值时:7 int hash = key.hashCode();8 int index = hash % Entry[].length;9 return Entry[index];

1)put

疑问:如果两个key通过hash%Entry[].length得到的index相同,会不会有覆盖的危险?

  这里HashMap里面用到链式数据结构的一个概念。上面我们提到过Entry类里面有一个next属性,作用是指向下一个Entry。打个比方, 第一个键值对A进来,通过计算其key的hash得到的index=0,记做:Entry[0] = A。一会后又进来一个键值对B,通过计算其index也等于0,现在怎么办?HashMap会这样做:B.next = A,Entry[0] = B,如果又进来C,index也等于0,那么C.next = B,Entry[0] = C;这样我们发现index=0的地方其实存取了A,B,C三个键值对,他们通过next这个属性链接在一起。所以疑问不用担心。也就是说数组中存储的是最后插入的元素。到这里为止,HashMap的大致实现,我们应该已经清楚了。

1 public V put(K key, V value) { 2         if (key == null) 3             return putForNullKey(value); //null总是放在数组的第一个链表中 4         int hash = hash(key.hashCode()); 5         int i = indexFor(hash, table.length); 6         //遍历链表 7         for (Entry
e = table[i]; e != null; e = e.next) { 8 Object k; 9 //如果key在链表中已存在,则替换为新value10 if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {11 V oldValue = e.value;12 e.value = value;13 e.recordAccess(this);14 return oldValue;15 }16 }17 modCount++;18 addEntry(hash, key, value, i);19 return null;20 }21 22 23 24 void addEntry(int hash, K key, V value, int bucketIndex) {25 Entry
e = table[bucketIndex];26 table[bucketIndex] = new Entry
(hash, key, value, e); //参数e, 是Entry.next27 //如果size超过threshold,则扩充table大小。再散列28 if (size++ >= threshold)29 resize(2 * table.length);30 }

当然HashMap里面也包含一些优化方面的实现,这里也说一下。比如:Entry[]的长度一定后,随着map里面数据的越来越长,这样同一个index的链就会很长,会不会影响性能?HashMap里面设置一个因子,随着map的size越来越大,Entry[]会以一定的规则加长长度。

 

2)get

public V get(Object key) {        if (key == null)            return getForNullKey();        int hash = hash(key.hashCode());        //先定位到数组元素,再遍历该元素处的链表        for (Entry
e = table[indexFor(hash, table.length)]; e != null; e = e.next) { Object k; if (e.hash == hash && ((k = e.key) == key || key.equals(k))) return e.value; } return null;}

 

3)null key的存取

null key总是存放在Entry[]数组的第一个元素。

1 private V putForNullKey(V value) { 2         for (Entry
e = table[0]; e != null; e = e.next) { 3 if (e.key == null) { 4 V oldValue = e.value; 5 e.value = value; 6 e.recordAccess(this); 7 return oldValue; 8 } 9 }10 modCount++;11 addEntry(0, null, value, 0);12 return null;13 }14 15 private V getForNullKey() {16 for (Entry
e = table[0]; e != null; e = e.next) {17 if (e.key == null)18 return e.value;19 }20 return null;21 }

 

4)确定数组index:hashcode % table.length取模

HashMap存取时,都需要计算当前key应该对应Entry[]数组哪个元素,即计算数组下标;算法如下:

/**     * Returns index for hash code h.     */    static int indexFor(int h, int length) {        return h & (length-1);    }
按位取并,作用上相当于取模mod或者取余%。
这意味着数组下标相同,并不表示hashCode相同。
 

5)table初始大小

1  public HashMap(int initialCapacity, float loadFactor) { 2         ..... 3         // Find a power of 2 >= initialCapacity 4         int capacity = 1; 5         while (capacity < initialCapacity) 6             capacity <<= 1; 7         this.loadFactor = loadFactor; 8         threshold = (int)(capacity * loadFactor); 9         table = new Entry[capacity];10         init();11     }

注意table初始大小并不是构造函数中的initialCapacity!!

而是 >= initialCapacity的2的n次幂!!!!

————为什么这么设计呢?——

3. 解决hash冲突的办法

  1. 开放定址法(线性探测再散列,二次探测再散列,伪随机探测再散列)
  2. 再哈希法
  3. 链地址法
  4. 建立一个公共溢出区

中hashmap的解决办法就是采用的链地址法。

 

4. 再散列rehash过程

当哈希表的容量超过默认容量时,必须调整table的大小。当容量已经达到最大可能值时,那么该方法就将容量调整到Integer.MAX_VALUE返回,这时,需要创建一张新表,将原表的映射到新表中。

1  /** 2      * Rehashes the contents of this map into a new array with a 3      * larger capacity.  This method is called automatically when the 4      * number of keys in this map reaches its threshold. 5      * 6      * If current capacity is MAXIMUM_CAPACITY, this method does not 7      * resize the map, but sets threshold to Integer.MAX_VALUE. 8      * This has the effect of preventing future calls. 9      *10      * @param newCapacity the new capacity, MUST be a power of two;11      *        must be greater than current capacity unless current12      *        capacity is MAXIMUM_CAPACITY (in which case value13      *        is irrelevant).14      */15     void resize(int newCapacity) {16         Entry[] oldTable = table;17         int oldCapacity = oldTable.length;18         if (oldCapacity == MAXIMUM_CAPACITY) {19             threshold = Integer.MAX_VALUE;20             return;21         }22         Entry[] newTable = new Entry[newCapacity];23         transfer(newTable);24         table = newTable;25         threshold = (int)(newCapacity * loadFactor);26     }27 28  29 30     /**31      * Transfers all entries from current table to newTable.32      */33     void transfer(Entry[] newTable) {34         Entry[] src = table;35         int newCapacity = newTable.length;36         for (int j = 0; j < src.length; j++) {37             Entry
e = src[j];38 if (e != null) {39 src[j] = null;40 do {41 Entry
next = e.next;42 //重新计算index43 int i = indexFor(e.hash, newCapacity);44 e.next = newTable[i];45 newTable[i] = e;46 e = next;47 } while (e != null);48 }49 }50 }

 

转载于:https://www.cnblogs.com/study-everyday/p/6373279.html

你可能感兴趣的文章
Unity 3D 我来了
查看>>
setup elk with docker-compose
查看>>
C++ GUI Qt4学习笔记03
查看>>
Java基础回顾 —反射机制
查看>>
c# 前台js 调用后台代码
查看>>
2017-02-20 可编辑div中如何在光标位置添加内容
查看>>
$.ajax()方法详解
查看>>
jquery操作select(增加,删除,清空)
查看>>
Sublimetext3安装Emmet插件步骤
查看>>
MySQL配置参数
查看>>
全面理解Java内存模型
查看>>
存储过程
查看>>
生成器
查看>>
将一个数的每一位都取出来的方法!
查看>>
2) 十分钟学会android--建立第一个APP,执行Android程序
查看>>
面试题8:二叉树下的一个节点
查看>>
hash冲突的解决方法
查看>>
Asp.Net webconfig中使用configSections的用法
查看>>
mysql 二进制日志
查看>>
阻止putty变成inactive
查看>>