自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

Java中HashMap的原理分析

開發(fā) 后端
HashMap在Java開發(fā)中有著非常重要的角色地位,每一個(gè)Java程序員都應(yīng)該了解HashMap。

[[171365]]

HashMap在Java開發(fā)中有著非常重要的角色地位,每一個(gè)Java程序員都應(yīng)該了解HashMap。詳細(xì)地闡述HashMap中的幾個(gè)概念,并深入探討HashMap的內(nèi)部結(jié)構(gòu)和實(shí)現(xiàn)細(xì)節(jié),討論HashMap的性能問題。

我們先來看這樣的一道面試題:

在 HashMap 中存放的一系列鍵值對(duì),其中鍵為某個(gè)我們自定義的類型。放入 HashMap 后,我們?cè)谕獠堪涯骋粋€(gè) key 的屬性進(jìn)行更改,然后我們?cè)儆眠@個(gè) key 從 HashMap 里取出元素,這時(shí)候 HashMap 會(huì)返回什么?

文中已給出示例代碼與答案,但關(guān)于HashMap的原理沒有做出解釋。

1. 特性

我們可以用任何類作為HashMap的key,但是對(duì)于這些類應(yīng)該有什么限制條件呢?且看下面的代碼:

  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,結(jié)果卻是null。對(duì)HashMap稍有了解的人看出來——Person類并沒有override hashcode方法,導(dǎo)致其繼承的是Object的hashcode(返回是其內(nèi)存地址)。這也是為什么常用不變類如String(或Integer等)做為HashMap的key的原因。那么,HashMap是如何利用hashcode給key做快速索引的呢?

2. 原理

首先,我們來看《Thinking in Java》中一個(gè)簡(jiǎn)單HashMap的實(shí)現(xiàn)方案:

  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構(gòu)造一個(gè)hash表來存儲(chǔ)key,hash函數(shù)是取模運(yùn)算Math.abs(key.hashCode()) % SIZE,采用鏈表法解決hash沖突;buckets的每一個(gè)槽位對(duì)應(yīng)存放具有相同(hash后)index值的Map.Entry,如下圖所示:

 

 

JDK的HashMap的實(shí)現(xiàn)原理與之相類似,其采用鏈地址的hash表table存儲(chǔ)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是對(duì)key的hashcode進(jìn)行hash后所得。當(dāng)要get key對(duì)應(yīng)的value時(shí),則對(duì)key計(jì)算其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函數(shù)的效率——好的hashcode會(huì)極大減少hash沖突,提高查詢性能。同時(shí),這也解釋開篇提出的兩個(gè)問題:如果自定義的類做HashMap的key,則hashcode的計(jì)算應(yīng)涵蓋構(gòu)造函數(shù)的所有字段,否則有可能得到null。

責(zé)任編輯:趙寧寧 來源: 互聯(lián)網(wǎng)
相關(guān)推薦

2015-06-15 10:12:36

Java原理分析

2015-08-10 15:12:27

Java實(shí)例源碼分析

2017-03-22 14:23:58

Java HashMa實(shí)現(xiàn)原理

2015-09-02 08:57:56

JavaHashMap工作原理

2023-07-11 08:00:00

2023-01-04 07:54:03

HashMap底層JDK

2014-04-28 10:17:01

2012-03-15 17:18:33

JavaHashMap

2012-03-15 16:12:57

JavaHashMap

2012-03-15 16:27:13

JavaHashMap

2021-09-10 06:50:03

HashMapHash方法

2013-06-06 13:10:44

HashMap無鎖

2023-10-18 10:55:55

HashMap

2011-02-22 09:40:18

HashMap

2022-12-28 09:10:44

HashMapImmutable類型

2009-02-27 08:56:30

IIS.Net原理分析

2023-10-10 08:39:25

Java 7Java 8

2009-03-26 13:43:59

實(shí)現(xiàn)Order ByMySQL

2023-02-07 09:17:19

Java注解原理

2020-11-20 14:02:22

HashMap遍歷Java
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)