欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

java中HashMap的原理分析

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

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

在 HashMap 中存放的一系列鍵值對,其中鍵為某個我們自定義的類型。放入 HashMap 后,我們在外部把某一個 key 的屬性進行更改,然后我們再用這個 key 從 HashMap 里取出元素,這時候 HashMap 會返回什么?

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

1. 特性

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

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

2. 原理

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

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

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

相關(guān)文章

  • apollo與springboot集成實現(xiàn)動態(tài)刷新配置的教程詳解

    apollo與springboot集成實現(xiàn)動態(tài)刷新配置的教程詳解

    這篇文章主要介紹了apollo與springboot集成實現(xiàn)動態(tài)刷新配置,本文分步驟給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2020-06-06
  • 淺談Java內(nèi)省機制

    淺談Java內(nèi)省機制

    本文主要介紹了Java內(nèi)省機制,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2022-08-08
  • SpringMVC攔截器運行原理及配置詳解

    SpringMVC攔截器運行原理及配置詳解

    這篇文章主要介紹了SpringMVC攔截器運行原理及配置詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2020-08-08
  • SpringSecurity添加圖形驗證碼認(rèn)證實現(xiàn)

    SpringSecurity添加圖形驗證碼認(rèn)證實現(xiàn)

    本文主要介紹了SpringSecurity添加圖形驗證碼認(rèn)證實現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2022-08-08
  • SpringBoot整合Mybatis-plus的具體使用

    SpringBoot整合Mybatis-plus的具體使用

    本文主要介紹了SpringBoot整合Mybatis-plus的具體使用,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2022-04-04
  • Java高級架構(gòu)之FastDFS分布式文件集群詳解

    Java高級架構(gòu)之FastDFS分布式文件集群詳解

    這篇文章主要介紹了Java高級架構(gòu)之FastDFS分布式文件集群詳解,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2019-04-04
  • Nacos源碼之注冊中心的實現(xiàn)詳解

    Nacos源碼之注冊中心的實現(xiàn)詳解

    這篇文章主要為大家介紹了Nacos源碼之注冊中心的實現(xiàn)詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2023-02-02
  • Java8中字符串處理庫strman-java的使用示例

    Java8中字符串處理庫strman-java的使用示例

    除了Java本身的字符串處理方式外,我們還可以使用Apache Common Langs里的StringUtils來簡化String的操作。但以上兩種方式對于我們?nèi)粘>幊讨凶钊菀着龅降淖址幚韥碚f,仍然顯得有些不足。所以這篇文章給大家介紹Java8中字符串處理庫strman-java的使用。
    2016-09-09
  • struts2靜態(tài)資源映射代碼示例

    struts2靜態(tài)資源映射代碼示例

    這篇文章主要介紹了struts2靜態(tài)資源映射的相關(guān)內(nèi)容,涉及了具體代碼示例,具有一定參考價值,需要的朋友可以了解下。
    2017-09-09
  • 詳細(xì)分析java 動態(tài)代理

    詳細(xì)分析java 動態(tài)代理

    這篇文章主要介紹了java 動態(tài)代理的的相關(guān)資料,文中講解非常細(xì)致,代碼幫助大家更好的理解和學(xué)習(xí),感興趣的朋友可以了解下
    2020-06-06

最新評論