激情久久久_欧美视频区_成人av免费_不卡视频一二三区_欧美精品在欧美一区二区少妇_欧美一区二区三区的

服務器之家:專注于服務器技術及軟件下載分享
分類導航

PHP教程|ASP.NET教程|Java教程|ASP教程|編程技術|正則表達式|C/C++|IOS|C#|Swift|Android|VB|R語言|JavaScript|易語言|vb.net|

服務器之家 - 編程語言 - Java教程 - java 中HashMap實現原理深入理解

java 中HashMap實現原理深入理解

2020-09-02 09:59AlphaWang Java教程

這篇文章主要介紹了java 中HashMap實現原理深入理解的相關資料,需要的朋友可以參考下

1. HashMap的數據結構

數據結構中有數組和鏈表來實現對數據的存儲,但這兩者基本上是兩個極端。

      數組

數組存儲區間是連續的,占用內存嚴重,故空間復雜的很大。但數組的二分查找時間復雜度小,為O(1);數組的特點是:尋址容易,插入和刪除困難;

鏈表

鏈表存儲區間離散,占用內存比較寬松,故空間復雜度很小,但時間復雜度很大,達O(N)。鏈表的特點是:尋址困難,插入和刪除容易。

哈希表

那么我們能不能綜合兩者的特性,做出一種尋址容易,插入刪除也容易的數據結構?答案是肯定的,這就是我們要提起的哈希表。哈希表((Hash table)既滿足了數據的查找方便,同時不占用太多的內容空間,使用也十分方便。

  哈希表有多種不同的實現方法,我接下來解釋的是最常用的一種方法—— 拉鏈法,我們可以理解為“鏈表的數組” ,如圖:

java 中HashMap實現原理深入理解

java 中HashMap實現原理深入理解

  從上圖我們可以發現哈希表是由數組+鏈表組成的,一個長度為16的數組中,每個元素存儲的是一個鏈表的頭結點。那么這些元素是按照什么樣的規則存儲到數組中呢。一般情況是通過hash(key)%len獲得,也就是元素的key的哈希值對數組長度取模得到。比如上述哈希表中,12%16=12,28%16=12,108%16=12,140%16=12。所以12、28、108以及140都存儲在數組下標為12的位置。

  HashMap其實也是一個線性的數組實現的,所以可以理解為其存儲數據的容器就是一個線性數組。這可能讓我們很不解,一個線性的數組怎么實現按鍵值對來存取數據呢?這里HashMap有做一些處理。

  首先HashMap里面實現一個靜態內部類Entry,其重要的屬性有key , value, next,從屬性key,value我們就能很明顯的看出來Entry就是HashMap鍵值對實現的一個基礎bean,我們上面說到HashMap的基礎就是一個線性數組,這個數組就是Entry[],Map里面的內容都保存在Entry[]里面。

java" id="highlighter_368286">
?
1
2
3
4
5
6
/**
 
   * The table, resized as necessary. Length MUST Always be a power of two.
 
   */
    transient Entry[] table;

2. HashMap的存取實現

     既然是線性數組,為什么能隨機存取?這里HashMap用了一個小算法,大致是這樣實現:

?
1
2
3
4
5
6
7
8
9
// 存儲時:
int hash = key.hashCode(); // 這個hashCode方法這里不詳述,只要理解每個key的hash是一個固定的int值
int index = hash % Entry[].length;
Entry[index] = value;
 
// 取值時:
int hash = key.hashCode();
int index = hash % Entry[].length;
return Entry[index];

1)put

疑問:如果兩個key通過hash%Entry[].length得到的index相同,會不會有覆蓋的危險?

  這里HashMap里面用到鏈式數據結構的一個概念。上面我們提到過Entry類里面有一個next屬性,作用是指向下一個Entry。打個比方, 第一個鍵值對A進來,通過計算其key的hash得到的index=0,記做:Entry[0] = A。一會后又進來一個鍵值對B,通過計算其index也等于0,現在怎么辦?HashMap會這樣做:B.next = A,Entry[0] = B,如果又進來C,index也等于0,那么C.next = B,Entry[0] = C;這樣我們發現index=0的地方其實存取了A,B,C三個鍵值對,他們通過next這個屬性鏈接在一起。所以疑問不用擔心。也就是說數組中存儲的是最后插入的元素。到這里為止,HashMap的大致實現,我們應該已經清楚了。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
public V put(K key, V value) {
 
   if (key == null)
 
     return putForNullKey(value); //null總是放在數組的第一個鏈表中
 
   int hash = hash(key.hashCode());
 
   int i = indexFor(hash, table.length);
 
   //遍歷鏈表
 
   for (Entry<K,V> e = table[i]; e != null; e = e.next) {
 
     Object k;
 
     //如果key在鏈表中已存在,則替換為新value
 
     if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
 
       V oldValue = e.value;
 
       e.value = value;
 
       e.recordAccess(this);
 
       return oldValue;
 
     }
 
   }
 
 
 
   modCount++;
 
   addEntry(hash, key, value, i);
 
   return null;
 
 }
?
1
2
3
4
5
6
7
8
9
10
11
12
13
void addEntry(int hash, K key, V value, int bucketIndex) {
 
  Entry<K,V> e = table[bucketIndex];
 
  table[bucketIndex] = new Entry<K,V>(hash, key, value, e);//參數e, 是Entry.next
 
  //如果size超過threshold,則擴充table大小。再散列
 
  if (size++ >= threshold)
 
      resize(2 * table.length);
 
}

  當然HashMap里面也包含一些優化方面的實現,這里也說一下。比如:Entry[]的長度一定后,隨著map里面數據的越來越長,這樣同一個index的鏈就會很長,會不會影響性能?HashMap里面設置一個因子,隨著map的size越來越大,Entry[]會以一定的規則加長長度。

2)get

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public V get(Object key) {
 
    if (key == null)
 
      return getForNullKey();
 
    int hash = hash(key.hashCode());
 
    //先定位到數組元素,再遍歷該元素處的鏈表
 
    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.equals(k)))
 
        return e.value;
 
    }
 
    return null;
 
}

 3)null key的存取

null key總是存放在Entry[]數組的第一個元素。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
private V putForNullKey(V value) {
 
   for (Entry<K,V> e = table[0]; e != null; e = e.next) {
 
     if (e.key == null) {
 
       V oldValue = e.value;
 
       e.value = value;
 
       e.recordAccess(this);
 
       return oldValue;
 
     }
 
   }
 
   modCount++;
 
   addEntry(0, null, value, 0);
 
   return null;
 
 }
 
 
 
 
 private V getForNullKey() {
 
   for (Entry<K,V> e = table[0]; e != null; e = e.next) {
 
     if (e.key == null)
 
       return e.value;
 
   }
 
   return null;
 
 }

 4)確定數組index:hashcode % table.length取模

HashMap存取時,都需要計算當前key應該對應Entry[]數組哪個元素,即計算數組下標;算法如下:

?
1
2
3
4
5
6
7
8
9
10
11
/**
 
  * Returns index for hash code h.
 
  */
 
 static int indexFor(int h, int length) {
 
   return h & (length-1);
 
 }

按位取并,作用上相當于取模mod或者取余%。

這意味著數組下標相同,并不表示hashCode相同。

5)table初始大小

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public HashMap(int initialCapacity, float loadFactor) {
 
   .....
 
 
   // Find a power of 2 >= initialCapacity
 
   int capacity = 1;
 
   while (capacity < initialCapacity)
 
     capacity <<= 1;
 
 
   this.loadFactor = loadFactor;
 
   threshold = (int)(capacity * loadFactor);
 
   table = new Entry[capacity];
 
   init();
 
 }

注意table初始大小并不是構造函數中的initialCapacity!!

而是 >= initialCapacity的2的n次冪!!!!

————為什么這么設計呢?——

3. 解決hash沖突的辦法開放定址法(線性探測再散列,二次探測再散列,偽隨機探測再散列) 再哈希法 鏈地址法 建立一個公共溢出區

Java中hashmap的解決辦法就是采用的鏈地址法。

4. 再散列rehash過程

當哈希表的容量超過默認容量時,必須調整table的大小。當容量已經達到最大可能值時,那么該方法就將容量調整到Integer.MAX_VALUE返回,這時,需要創建一張新表,將原表的映射到新表中。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
/**
 
 * Rehashes the contents of this map into a new array with a
 
 * larger capacity. This method is called automatically when the
 
 * number of keys in this map reaches its threshold.
 
 *
 
 * If current capacity is MAXIMUM_CAPACITY, this method does not
 
 * resize the map, but sets threshold to Integer.MAX_VALUE.
 
 * This has the effect of preventing future calls.
 
 *
 
 * @param newCapacity the new capacity, MUST be a power of two;
 
 *    must be greater than current capacity unless current
 
 *    capacity is MAXIMUM_CAPACITY (in which case value
 
 *    is irrelevant).
 
 */
 
void resize(int newCapacity) {
 
  Entry[] oldTable = table;
 
  int oldCapacity = oldTable.length;
 
  if (oldCapacity == MAXIMUM_CAPACITY) {
 
    threshold = Integer.MAX_VALUE;
 
    return;
 
  }
 
 
  Entry[] newTable = new Entry[newCapacity];
 
  transfer(newTable);
 
  table = newTable;
 
  threshold = (int)(newCapacity * loadFactor);
 
}
 
 
 
/**
 
 * Transfers all entries from current table to newTable.
 
 */
 
void transfer(Entry[] newTable) {
 
  Entry[] src = table;
 
  int newCapacity = newTable.length;
 
  for (int j = 0; j < src.length; j++) {
 
    Entry<K,V> e = src[j];
 
    if (e != null) {
 
      src[j] = null;
 
      do {
 
        Entry<K,V> next = e.next;
 
        //重新計算index
 
        int i = indexFor(e.hash, newCapacity);
 
        e.next = newTable[i];
 
        newTable[i] = e;
 
        e = next;
 
      } while (e != null);
 
    }
 
  }
 
}

感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!

原文鏈接:http://blog.csdn.net/vking_wang/article/details/14166593

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 成人激情久久 | av成人免费观看 | 欧美成人免费一级 | 一色屋任你操 | 免费午夜网站 | 久久夜靖品2区 | 一级做a爰性色毛片免费 | 久久久久九九九女人毛片 | 在线观看av国产一区二区 | 精品亚洲夜色av98在线观看 | 久久国产精品一区 | 国产精品久久99精品毛片三a | 成人视屏在线观看 | 国产精品91久久久 | 久久久久久久久久网 | 国产精品久久久久久久四虎电影 | 亚洲成人午夜精品 | 成人一级毛片 | 性片网站| 国产亚洲精品久久久久5区 99精品视频在线 | 欧美性受xxxx白人性爽 | 成人午夜在线观看视频 | hd porn 4k video xhicial| 久久久三区 | 99爱视频 | 国产小视频在线 | 亚洲精品7777xxxx青睐 | 色戒在线版 | 中文字幕在线亚洲精品 | 九九视屏| 久久久资源网 | 视频h在线 | 国内精品久久久久久久久久 | 狠狠婷婷综合久久久久久妖精 | 午夜久 | 国产午夜精品在线 | 黄色毛片观看 | 毛片免费视频播放 | 在线看一区二区三区 | 午夜色片| 欧美极品欧美精品欧美视频 |