Java中HashMap的原理分析

开发 后端
HashMap在Java开发中有着非常重要的角色地位,每一个Java程序员都应该了解HashMap。

[[171365]]

HashMap在Java开发中有着非常重要的角色地位,每一个Java程序员都应该了解HashMap。详细地阐述HashMap中的几个概念,并深入探讨HashMap的内部结构和实现细节,讨论HashMap的性能问题。

我们先来看这样的一道面试题:

在 HashMap 中存放的一系列键值对,其中键为某个我们自定义的类型。放入 HashMap 后,我们在外部把某一个 key 的属性进行更改,然后我们再用这个 key 从 HashMap 里取出元素,这时候 HashMap 会返回什么?

文中已给出示例代码与答案,但关于HashMap的原理没有做出解释。

1. 特性

我们可以用任何类作为HashMap的key,但是对于这些类应该有什么限制条件呢?且看下面的代码:

  1. public class Person { 
  2.   private String name; 
  3.   
  4.   public Person(String name) { 
  5.     this.name = name; 
  6.   } 
  7.   
  8. Map<Person, String> testMap = new HashMap<>(); 
  9. testMap.put(new Person("hello"), "world"); 
  10. testMap.get(new Person("hello")); // ---> null 

本是想取出具有相等字段值Person类的value,结果却是null。对HashMap稍有了解的人看出来——Person类并没有override hashcode方法,导致其继承的是Object的hashcode(返回是其内存地址)。这也是为什么常用不变类如String(或Integer等)做为HashMap的key的原因。那么,HashMap是如何利用hashcode给key做快速索引的呢?

2. 原理

首先,我们来看《Thinking in Java》中一个简单HashMap的实现方案:

  1. //: containers/SimpleHashMap.java 
  2. // A demonstration hashed Map. 
  3. import java.util.*; 
  4. import net.mindview.util.*; 
  5.   
  6. public class SimpleHashMap<K,V> extends AbstractMap<K,V> { 
  7.  // Choose a prime number for the hash table size, to achieve a uniform distribution: 
  8.  static final int SIZE = 997
  9.  // You can't have a physical array of generics, but you can upcast to one: 
  10.  @SuppressWarnings("unchecked") 
  11.  LinkedList<MapEntry<K,V>>[] buckets = 
  12.   new LinkedList[SIZE]; 
  13.  public V put(K key, V value) { 
  14.   V oldValue = null
  15.   int index = Math.abs(key.hashCode()) % SIZE; 
  16.   if(buckets[index] == null) 
  17.    buckets[index] = new LinkedList<MapEntry<K,V>>(); 
  18.   LinkedList<MapEntry<K,V>> bucket = buckets[index]; 
  19.   MapEntry<K,V> pair = new MapEntry<K,V>(key, value); 
  20.   boolean found = false
  21.   ListIterator<MapEntry<K,V>> it = bucket.listIterator(); 
  22.   while(it.hasNext()) { 
  23.    MapEntry<K,V> iPair = it.next(); 
  24.    if(iPair.getKey().equals(key)) { 
  25.     oldValue = iPair.getValue(); 
  26.     it.set(pair); // Replace old with new 
  27.     found = true
  28.     break; 
  29.    } 
  30.   } 
  31.   if(!found) 
  32.    buckets[index].add(pair); 
  33.   return oldValue; 
  34.  } 
  35.  public V get(Object key) { 
  36.   int index = Math.abs(key.hashCode()) % SIZE; 
  37.   if(buckets[index] == null) return null; 
  38.   for(MapEntry<K,V> iPair : buckets[index]) 
  39.    if(iPair.getKey().equals(key)) 
  40.     return iPair.getValue(); 
  41.   return null; 
  42.  } 
  43.  public Set<Map.Entry<K,V>> entrySet() { 
  44.   Set<Map.Entry<K,V>> setnew HashSet<Map.Entry<K,V>>(); 
  45.   for(LinkedList<MapEntry<K,V>> bucket : buckets) { 
  46.    if(bucket == null) continue; 
  47.    for(MapEntry<K,V> mpair : bucket) 
  48.     set.add(mpair); 
  49.   } 
  50.   return set; 
  51.  } 
  52.  public static void main(String[] args) { 
  53.   SimpleHashMap<String,String> m = 
  54.    new SimpleHashMap<String,String>(); 
  55.   m.putAll(Countries.capitals(25)); 
  56.   System.out.println(m); 
  57.   System.out.println(m.get("ERITREA")); 
  58.   System.out.println(m.entrySet()); 
  59.  } 

SimpleHashMap构造一个hash表来存储key,hash函数是取模运算Math.abs(key.hashCode()) % SIZE,采用链表法解决hash冲突;buckets的每一个槽位对应存放具有相同(hash后)index值的Map.Entry,如下图所示:

 

 

JDK的HashMap的实现原理与之相类似,其采用链地址的hash表table存储Map.Entry:

  1. /** 
  2.  * The table, resized as necessary. Length MUST Always be a power of two. 
  3.  */ 
  4. transient Entry<K,V>[] table = (Entry<K,V>[]) EMPTY_TABLE; 
  5.   
  6. static class Entry<K,V> implements Map.Entry<K,V> { 
  7.   final K key; 
  8.   V value; 
  9.   Entry<K,V> next; 
  10.   int hash; 
  11.   … 

Map.Entry的index是对key的hashcode进行hash后所得。当要get key对应的value时,则对key计算其index,然后在table中取出Map.Entry即可得到,具体参看代码:

  1. public V get(Object key) { 
  2.   if (key == null) 
  3.     return getForNullKey(); 
  4.   Entry<K,V> entry = getEntry(key); 
  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.   
  13.   int hash = (key == null) ? 0 : hash(key); 
  14.   for (Entry<K,V> e = table[indexFor(hash, table.length)]; 
  15.      e != null; 
  16.      ee = 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; 

可见,hashcode直接影响HashMap的hash函数的效率——好的hashcode会极大减少hash冲突,提高查询性能。同时,这也解释开篇提出的两个问题:如果自定义的类做HashMap的key,则hashcode的计算应涵盖构造函数的所有字段,否则有可能得到null。

责任编辑:赵宁宁 来源: 互联网
相关推荐

2015-06-15 10:12:36

Java原理分析

2015-08-10 15:12:27

Java实例源码分析

2015-09-02 08:57:56

JavaHashMap工作原理

2017-03-22 14:23:58

Java HashMa实现原理

2014-04-28 10:17:01

2023-07-11 08:00:00

2023-01-04 07:54:03

HashMap底层JDK

2012-03-15 17:18:33

JavaHashMap

2012-03-15 16:27:13

JavaHashMap

2012-03-15 16:12:57

JavaHashMap

2011-02-22 09:40:18

HashMap

2021-09-10 06:50:03

HashMapHash方法

2013-06-06 13:10:44

HashMap无锁

2023-10-18 10:55:55

HashMap

2023-10-10 08:39:25

Java 7Java 8

2022-12-28 09:10:44

HashMapImmutable类型

2009-02-27 08:56:30

IIS.Net原理分析

2020-11-20 14:02:22

HashMap遍历Java

2021-12-13 10:43:45

HashMapJava集合容器

2009-03-26 13:43:59

实现Order ByMySQL
点赞
收藏

51CTO技术栈公众号