最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

java中HashMap的原理分析

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

我們先來(lái)看這樣的一道面試題:

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

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

1. 特性

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

2. 原理

首先,我們來(lái)看《Thinking in Java》中一個(gè)簡(jiǎn)單HashMap的實(shí)現(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)造一個(gè)hash表來(lái)存儲(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)原理與之相類(lèi)似,其采用鏈地址的hash表table存儲(chǔ)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是對(duì)key的hashcode進(jìn)行hash后所得。當(dāng)要get key對(duì)應(yīng)的value時(shí),則對(duì)key計(jì)算其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;
}

可見(jiàn),hashcode直接影響HashMap的hash函數(shù)的效率——好的hashcode會(huì)極大減少hash沖突,提高查詢(xún)性能。同時(shí),這也解釋開(kāi)篇提出的兩個(gè)問(wèn)題:如果自定義的類(lèi)做HashMap的key,則hashcode的計(jì)算應(yīng)涵蓋構(gòu)造函數(shù)的所有字段,否則有可能得到null。

相關(guān)文章

最新評(píng)論

滦南县| 班玛县| 平阴县| 阿克苏市| 和林格尔县| 朝阳市| 武乡县| 会泽县| 江阴市| 黎平县| 根河市| 新丰县| 石阡县| 石门县| 新野县| 寿光市| 西青区| 平安县| 梅州市| 二连浩特市| 百色市| 沙河市| 定结县| 余姚市| 衡水市| 庄浪县| 阳江市| 甘泉县| 乌兰浩特市| 通江县| 浦东新区| 晋宁县| 丰城市| 个旧市| 长葛市| 射洪县| 双柏县| 耿马| 黑龙江省| 宣威市| 垦利县|