Java集合詳解(五):Hashtable原理解析

Yanci丶發表於2021-05-26

概述

  本文是基於jdk8_271版本進行分析的。
  Hashtable與HashMap一樣,是一個儲存key-value的雙列集合。底層是基於陣列+連結串列實現的,沒有紅黑樹結構。Hashtable預設初始化容量為11,Hashtable也會動態擴容,與HashMap不同的是,每次擴容的容量是原容量2倍+1。Hashtable的key和value都不允許為null。Hashtable在方法上都加了synchronized同步鎖。所以Hashtable是執行緒安全的,同時Hashtable的效率也相對較低。

資料結構

  • 實現繼承關係

1 public class Hashtable<K,V>
2     extends Dictionary<K,V>
3     implements Map<K,V>, Cloneable, java.io.Serializable
  1. Dictionary:
  2. Map:
  3. Cloneable:
  4. Serializable:
  • 成員變數

 1     // 存放hash表資料
 2     private transient Entry<?,?>[] table;
 3 
 4     // 元素數量
 5     private transient int count;
 6 
 7     // 閾值。元素數量達到該值,進行擴容
 8     private int threshold;
 9 
10     // 載入因子,預設是0.75
11     private float loadFactor;
12 
13     // 修改次數
14     private transient int modCount = 0;
  • 建構函式

  Hashtable預設初始化容量為11,預設載入因子的值為0.75(與HashMap一樣)。選擇0.75作為預設的載入因子,完全是時間和空間成本上尋求的一種折中選擇。載入因子過高雖然減少了空間開銷,但同時也增加了查詢成本;載入因子過低雖然可以減少查詢時間成本,但是空間利用率很低。

  Hashtable初始化容量值使用傳入的值(0除外),不會重新計算(HashMap需要重新計算,使得容量大小為2的指數次冪)。在構造方法建立物件時,會直接初始化陣列,沒有采用懶載入的方式。

 1     public Hashtable(int initialCapacity, float loadFactor) {
 2         if (initialCapacity < 0)
 3             throw new IllegalArgumentException("Illegal Capacity: "+
 4                                                initialCapacity);
 5         if (loadFactor <= 0 || Float.isNaN(loadFactor))
 6             throw new IllegalArgumentException("Illegal Load: "+loadFactor);
 7         // 如果初始化容量傳入的是0,則預設使用1
 8         if (initialCapacity==0)
 9             initialCapacity = 1;
10         this.loadFactor = loadFactor;
11         table = new Entry<?,?>[initialCapacity];
12         // 計算閾值。預計的閾值為初始化容量*載入因子,預計的閾值如果大於MAX_ARRAY_SIZE + 1,則實際閾值設定為MAX_ARRAY_SIZE + 1
13         threshold = (int)Math.min(initialCapacity * loadFactor, MAX_ARRAY_SIZE + 1);
14     }
15 
16     public Hashtable(int initialCapacity) {
17         // 傳入初始化容量,載入因子使用預設值0.75。初始化容量傳入的是多少就初始化多大(0除外;傳入的如果0,預設使用1),不需要再重新計算
18         this(initialCapacity, 0.75f);
19     }
20 
21     public Hashtable() {
22         // 預設初始化容量11,預設載入因子0.75
23         this(11, 0.75f);
24     }
25 
26     public Hashtable(Map<? extends K, ? extends V> t) {
27         // 初始化容量為傳入集合元素數量的2倍(至少為11),載入因子使用預設值0.75
28         this(Math.max(2*t.size(), 11), 0.75f);
29         putAll(t);
30     }

主要方法解析

  • 擴容方法

  這裡與HashMap擴容時候有點區別,連結串列資料遷移時候,Hashtable是在連結串列頭部插入(和之前連結串列反過來),HashMap是在尾部插入。

 1     protected void rehash() {
 2         int oldCapacity = table.length; // 原容量值
 3         Entry<?,?>[] oldMap = table;    // 原陣列
 4 
 5         // overflow-conscious code
 6         int newCapacity = (oldCapacity << 1) + 1;   // 預計擴容的容量為原容量的2倍+1
 7         if (newCapacity - MAX_ARRAY_SIZE > 0) {
 8             if (oldCapacity == MAX_ARRAY_SIZE)  // 預計擴容容量如果大於容量最大值,並且原容量為容量最大值,則不進行擴容處理
 9                 // Keep running with MAX_ARRAY_SIZE buckets
10                 return;
11             newCapacity = MAX_ARRAY_SIZE;   // 預計擴容容量如果大於容量最大值,則將新容量設定為容量最大值
12         }
13         Entry<?,?>[] newMap = new Entry<?,?>[newCapacity];  // 構建一個新陣列
14 
15         modCount++; // 修改次數+1
16         // 計算閾值。新容量值*載入因子,與容量最大值+1,兩個比較取最小值
17         threshold = (int)Math.min(newCapacity * loadFactor, MAX_ARRAY_SIZE + 1);
18         table = newMap;
19 
20         for (int i = oldCapacity ; i-- > 0 ;) {
21             // 遍歷原陣列,從後往前
22             for (Entry<K,V> old = (Entry<K,V>)oldMap[i] ; old != null ; ) {
23                 // 遍歷該索引位連結串列,這裡與jdk8中hashmap有點區別,這裡是在連結串列頭部插入(和之前連結串列會反過來),hashmap是在尾部插入
24                 Entry<K,V> e = old;
25                 old = old.next;
26 
27                 int index = (e.hash & 0x7FFFFFFF) % newCapacity;
28                 e.next = (Entry<K,V>)newMap[index];
29                 newMap[index] = e;
30             }
31         }
32     }
  • 新增元素

  新增元素時,Hashtable與HashMap有3點區別:

  1. Hashtable的key-value都不允許為null。
  2. Hashtable是在連結串列頭部插入(和之前連結串列反過來),HashMap是在尾部插入。
  3. Hashtable是先判斷是否需要擴容,再插入元素;jdk8HashMap是先插入元素再判斷是否需要擴容。
 1     public synchronized V put(K key, V value) {
 2         // Make sure the value is not null
 3         if (value == null) {
 4             // value為空,會丟擲空指標異常
 5             throw new NullPointerException();
 6         }
 7 
 8         // Makes sure the key is not already in the hashtable.
 9         Entry<?,?> tab[] = table;
10         int hash = key.hashCode();
11         int index = (hash & 0x7FFFFFFF) % tab.length;
12         @SuppressWarnings("unchecked")
13         Entry<K,V> entry = (Entry<K,V>)tab[index];
14         for(; entry != null ; entry = entry.next) {
15             if ((entry.hash == hash) && entry.key.equals(key)) {
16                 // 該key已經存在,直接替換原值
17                 V old = entry.value;
18                 entry.value = value;
19                 return old;
20             }
21         }
22         // 新增元素
23         addEntry(hash, key, value, index);
24         return null;
25     }
26     private void addEntry(int hash, K key, V value, int index) {
27         modCount++;
28 
29         Entry<?,?> tab[] = table;
30         if (count >= threshold) {   // 判斷是否元素數量是否達到閾值,如果達到先進行擴容處理
31             // Rehash the table if the threshold is exceeded
32             rehash();
33 
34             tab = table;
35             hash = key.hashCode();
36             index = (hash & 0x7FFFFFFF) % tab.length;
37         }
38 
39         // Creates the new entry.
40         @SuppressWarnings("unchecked")
41         Entry<K,V> e = (Entry<K,V>) tab[index];
42         // 插入元素是在連結串列頭部插入
43         tab[index] = new Entry<>(hash, key, value, e);
44         count++;
45     }
  • 刪除元素

 1     public synchronized V remove(Object key) {
 2         Entry<?,?> tab[] = table;
 3         int hash = key.hashCode();
 4         int index = (hash & 0x7FFFFFFF) % tab.length;
 5         @SuppressWarnings("unchecked")
 6         Entry<K,V> e = (Entry<K,V>)tab[index];
 7         for(Entry<K,V> prev = null ; e != null ; prev = e, e = e.next) {
 8             if ((e.hash == hash) && e.key.equals(key)) {
 9                 modCount++;
10                 if (prev != null) {
11                     prev.next = e.next;
12                 } else {
13                     tab[index] = e.next;
14                 }
15                 count--;
16                 V oldValue = e.value;
17                 e.value = null;
18                 return oldValue;
19             }
20         }
21         return null;
22     }
23     public synchronized boolean remove(Object key, Object value) {
24         Objects.requireNonNull(value);
25 
26         Entry<?,?> tab[] = table;
27         int hash = key.hashCode();
28         int index = (hash & 0x7FFFFFFF) % tab.length;
29         @SuppressWarnings("unchecked")
30         Entry<K,V> e = (Entry<K,V>)tab[index];
31         for (Entry<K,V> prev = null; e != null; prev = e, e = e.next) {
32             if ((e.hash == hash) && e.key.equals(key) && e.value.equals(value)) {
33                 modCount++;
34                 if (prev != null) {
35                     prev.next = e.next;
36                 } else {
37                     tab[index] = e.next;
38                 }
39                 count--;
40                 e.value = null;
41                 return true;
42             }
43         }
44         return false;
45     }
  • 序列化/反序列化方法

 1     private void writeObject(java.io.ObjectOutputStream s)
 2             throws IOException {
 3         Entry<Object, Object> entryStack = null;
 4 
 5         synchronized (this) {
 6             // Write out the threshold and loadFactor
 7             s.defaultWriteObject();
 8 
 9             // Write out the length and count of elements
10             s.writeInt(table.length);
11             s.writeInt(count);
12 
13             // Stack copies of the entries in the table
14             for (int index = 0; index < table.length; index++) {
15                 Entry<?,?> entry = table[index];
16 
17                 while (entry != null) {
18                     entryStack =
19                         new Entry<>(0, entry.key, entry.value, entryStack);
20                     entry = entry.next;
21                 }
22             }
23         }
24 
25         // Write out the key/value objects from the stacked entries
26         while (entryStack != null) {
27             s.writeObject(entryStack.key);
28             s.writeObject(entryStack.value);
29             entryStack = entryStack.next;
30         }
31     }
32 
33     private void readObject(java.io.ObjectInputStream s)
34          throws IOException, ClassNotFoundException
35     {
36         // Read in the threshold and loadFactor
37         s.defaultReadObject();
38 
39         // Validate loadFactor (ignore threshold - it will be re-computed)
40         if (loadFactor <= 0 || Float.isNaN(loadFactor))
41             throw new StreamCorruptedException("Illegal Load: " + loadFactor);
42 
43         // Read the original length of the array and number of elements
44         int origlength = s.readInt();
45         int elements = s.readInt();
46 
47         // Validate # of elements
48         if (elements < 0)
49             throw new StreamCorruptedException("Illegal # of Elements: " + elements);
50 
51         // Clamp original length to be more than elements / loadFactor
52         // (this is the invariant enforced with auto-growth)
53         origlength = Math.max(origlength, (int)(elements / loadFactor) + 1);
54 
55         // Compute new length with a bit of room 5% + 3 to grow but
56         // no larger than the clamped original length.  Make the length
57         // odd if it's large enough, this helps distribute the entries.
58         // Guard against the length ending up zero, that's not valid.
59         int length = (int)((elements + elements / 20) / loadFactor) + 3;
60         if (length > elements && (length & 1) == 0)
61             length--;
62         length = Math.min(length, origlength);
63 
64         if (length < 0) { // overflow
65             length = origlength;
66         }
67 
68         // Check Map.Entry[].class since it's the nearest public type to
69         // what we're actually creating.
70         SharedSecrets.getJavaOISAccess().checkArray(s, Map.Entry[].class, length);
71         table = new Entry<?,?>[length];
72         threshold = (int)Math.min(length * loadFactor, MAX_ARRAY_SIZE + 1);
73         count = 0;
74 
75         // Read the number of elements and then all the key/value objects
76         for (; elements > 0; elements--) {
77             @SuppressWarnings("unchecked")
78                 K key = (K)s.readObject();
79             @SuppressWarnings("unchecked")
80                 V value = (V)s.readObject();
81             // sync is eliminated for performance
82             reconstitutionPut(table, key, value);
83         }
84     }

 

Dictionary

相關文章