java中HashMap的原理分析_java

來源:互聯網
上載者:User

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

在 HashMap 中存放的一系列索引值對,其中鍵為某個我們自訂的類型。放入 HashMap 後,我們在外部把某一個 key 的屬性變更,然後我們再用這個 key 從 HashMap 裡取出元素,這時候 HashMap 會返回什嗎?

文中已給出範例程式碼與答案,但關於HashMap的原理沒有做出解釋。

1. 特性

我們可以用任何類作為HashMap的key,但是對於這些類應該有什麼限制條件呢?且看下面的代碼:

public class Person {  private String name;  public Person(String name) {    this.name = name;  }}Map<Person, String> testMap = new HashMap<>();testMap.put(new Person("hello"), "world");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的實現方案:

//: containers/SimpleHashMap.java// A demonstration hashed Map.import java.util.*;import net.mindview.util.*;public class SimpleHashMap<K,V> extends AbstractMap<K,V> { // Choose a prime number for the hash table size, to achieve a uniform distribution: static final int SIZE = 997; // You can't have a physical array of generics, but you can upcast to one: @SuppressWarnings("unchecked") LinkedList<MapEntry<K,V>>[] buckets =  new LinkedList[SIZE]; public V put(K key, V value) {  V oldValue = null;  int index = Math.abs(key.hashCode()) % SIZE;  if(buckets[index] == null)   buckets[index] = new LinkedList<MapEntry<K,V>>();  LinkedList<MapEntry<K,V>> bucket = buckets[index];  MapEntry<K,V> pair = new MapEntry<K,V>(key, value);  boolean found = false;  ListIterator<MapEntry<K,V>> it = bucket.listIterator();  while(it.hasNext()) {   MapEntry<K,V> iPair = it.next();   if(iPair.getKey().equals(key)) {    oldValue = iPair.getValue();    it.set(pair); // Replace old with new    found = true;    break;   }  }  if(!found)   buckets[index].add(pair);  return oldValue; } public V get(Object key) {  int index = Math.abs(key.hashCode()) % SIZE;  if(buckets[index] == null) return null;  for(MapEntry<K,V> iPair : buckets[index])   if(iPair.getKey().equals(key))    return iPair.getValue();  return null; } public Set<Map.Entry<K,V>> entrySet() {  Set<Map.Entry<K,V>> set= new HashSet<Map.Entry<K,V>>();  for(LinkedList<MapEntry<K,V>> bucket : buckets) {   if(bucket == null) continue;   for(MapEntry<K,V> mpair : bucket)    set.add(mpair);  }  return set; } public static void main(String[] args) {  SimpleHashMap<String,String> m =   new SimpleHashMap<String,String>();  m.putAll(Countries.capitals(25));  System.out.println(m);  System.out.println(m.get("ERITREA"));  System.out.println(m.entrySet()); }}

SimpleHashMap構造一個hash表來儲存key,hash函數是模數運算Math.abs(key.hashCode()) % SIZE,採用鏈表法解決hash衝突;buckets的每一個槽位對應存放具有相同(hash後)index值的Map.Entry,如下圖所示:

JDK的HashMap的實現原理與之相類似,其採用鏈地址的hash表table儲存Map.Entry:

/** * The table, resized as necessary. Length MUST Always be a power of two. */transient Entry<K,V>[] table = (Entry<K,V>[]) EMPTY_TABLE;static class Entry<K,V> implements Map.Entry<K,V> {  final K key;  V value;  Entry<K,V> next;  int hash;  …}

Map.Entry的index是對key的hashcode進行hash後所得。當要get key對應的value時,則對key計算其index,然後在table中取出Map.Entry即可得到,具體參看代碼:

public V get(Object key) {  if (key == null)    return getForNullKey();  Entry<K,V> entry = getEntry(key);  return null == entry ? null : entry.getValue();}final Entry<K,V> getEntry(Object key) {  if (size == 0) {    return null;  }  int hash = (key == null) ? 0 : hash(key);  for (Entry<K,V> e = table[indexFor(hash, table.length)];     e != null;     e = e.next) {    Object k;    if (e.hash == hash &&      ((k = e.key) == key || (key != null && key.equals(k))))      return e;  }  return null;}

可見,hashcode直接影響HashMap的hash函數的效率——好的hashcode會極大減少hash衝突,提高查詢效能。同時,這也解釋開篇提出的兩個問題:如果自訂的類做HashMap的key,則hashcode的計算應涵蓋建構函式的所有欄位,否則有可能得到null。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.