HashTable源碼分析

轉自:

和HashMap一樣,Hashtable 也是一個散列表,它存儲的內容是鍵值對(key-value)映射

Hashtable 繼承於Dictionary,實現了Map、Cloneable、java.io.Serializable接口。
Hashtable 的函數都是同步的,這意味着它是線程安全的。它的key、value都可以爲null。此外,Hashtable中的映射不是有序的。
通常,默認加載因子是 0.75, 這是在時間和空間成本上尋求一種折衷。加載因子過高雖然減少了空間開銷,但同時也增加了查找某個條目的時間(在大多數 Hashtable 操作中,包括 get 和 put 操作,都反映了這一點)。

Hashtable 的實例有兩個參數影響其性能:初始容量 和 加載因子。容量 是哈希表中桶 的數量,初始容量 就是哈希表創建時的容量。注意,哈希表的狀態爲 open:在發生“哈希衝突”的情況下,單個桶會存儲多個條目,這些條目必須按順序搜索。加載因子 是對哈希表在其容量自動增加之前可以達到多滿的一個尺度。初始容量和加載因子這兩個參數只是對該實現的提示。關於何時以及是否調用 rehash 方法的具體細節則依賴於該實現。


  1. public class Hashtable<K,V>  
  2.     extends Dictionary<K,V>  
  3.     implements Map<K,V>, Cloneable, java.io.Serializable {  
  4.  
  5.     // Hashtable保存key-value的數組。 
  6.     // Hashtable是採用拉鍊法實現的,每一個Entry本質上是一個單向鏈表 
  7.     private transient Entry[] table;  
  8.  
  9.     // Hashtable中元素的實際數量 
  10.     private transient int count;  
  11.  
  12.     // 閾值,用於判斷是否需要調整Hashtable的容量(threshold = 容量*加載因子) 
  13.     private int threshold;  
  14.  
  15.     // 加載因子 
  16.     private float loadFactor;  
  17.  
  18.     // Hashtable被改變的次數 
  19.     private transient int modCount = 0;  
  20.  
  21.     // 序列版本號 
  22.     private static final long serialVersionUID = 1421746759512286392L;  
  23.  
  24.     // 指定“容量大小”和“加載因子”的構造函數 
  25.     public Hashtable(int initialCapacity, float loadFactor) {  
  26.         if (initialCapacity < 0)  
  27.             throw new IllegalArgumentException("Illegal Capacity: "+  
  28.                                                initialCapacity);  
  29.         if (loadFactor <= 0 || Float.isNaN(loadFactor))  
  30.             throw new IllegalArgumentException("Illegal Load: "+loadFactor);  
  31.  
  32.         if (initialCapacity==0)  
  33.             initialCapacity = 1;  
  34.         this.loadFactor = loadFactor;  
  35.         table = new Entry[initialCapacity];  
  36.         threshold = (int)(initialCapacity * loadFactor);  
  37.     }  
  38.  
  39.     // 指定“容量大小”的構造函數 
  40.     public Hashtable(int initialCapacity) {  
  41.         this(initialCapacity, 0.75f);  
  42.     }  
  43.  
  44.     // 默認構造函數。 
  45.     public Hashtable() {  
  46.         // 默認構造函數,指定的容量大小是11;加載因子是0.75 
  47.         this(110.75f);  
  48.     }  
  49.  
  50.     // 包含“子Map”的構造函數 
  51.     public Hashtable(Map<? extends K, ? extends V> t) {  
  52.         this(Math.max(2*t.size(), 11), 0.75f);  
  53.         // 將“子Map”的全部元素都添加到Hashtable中 
  54.         putAll(t);  
  55.     }  
  56.  
  57.     public synchronized int size() {  
  58.         return count;  
  59.     }  
  60.  
  61.     public synchronized boolean isEmpty() {  
  62.         return count == 0;  
  63.     }  
  64.  
  65.     // 返回“所有key”的枚舉對象 
  66.     public synchronized Enumeration<K> keys() {  
  67.         return this.<K>getEnumeration(KEYS);  
  68.     }  
  69.  
  70.     // 返回“所有value”的枚舉對象 
  71.     public synchronized Enumeration<V> elements() {  
  72.         return this.<V>getEnumeration(VALUES);  
  73.     }  
  74.  
  75.     // 判斷Hashtable是否包含“值(value)” 
  76.     public synchronized boolean contains(Object value) {  
  77.         // Hashtable中“鍵值對”的value不能是null, 
  78.         // 若是null的話,拋出異常! 
  79.         if (value == null) {  
  80.             throw new NullPointerException();  
  81.         }  
  82.  
  83.         // 從後向前遍歷table數組中的元素(Entry) 
  84.         // 對於每個Entry(單向鏈表),逐個遍歷,判斷節點的值是否等於value 
  85.         Entry tab[] = table;  
  86.         for (int i = tab.length ; i-- > 0 ;) {  
  87.             for (Entry<K,V> e = tab[i] ; e != null ; e = e.next) {  
  88.                 if (e.value.equals(value)) {  
  89.                     return true;  
  90.                 }  
  91.             }  
  92.         }  
  93.         return false;  
  94.     }  
  95.  
  96.     public boolean containsValue(Object value) {  
  97.         return contains(value);  
  98.     }  
  99.  
  100.     // 判斷Hashtable是否包含key 
  101.     public synchronized boolean containsKey(Object key) {  
  102.         Entry tab[] = table;  
  103.         int hash = key.hashCode();  
  104.         // 計算索引值, 
  105.         // % tab.length 的目的是防止數據越界 
  106.         int index = (hash & 0x7FFFFFFF) % tab.length;  
  107.         // 找到“key對應的Entry(鏈表)”,然後在鏈表中找出“哈希值”和“鍵值”與key都相等的元素 
  108.         for (Entry<K,V> e = tab[index] ; e != null ; e = e.next) {  
  109.             if ((e.hash == hash) && e.key.equals(key)) {  
  110.                 return true;  
  111.             }  
  112.         }  
  113.         return false;  
  114.     }  
  115.  
  116.     // 返回key對應的value,沒有的話返回null 
  117.     public synchronized V get(Object key) {  
  118.         Entry tab[] = table;  
  119.         int hash = key.hashCode();  
  120.         // 計算索引值, 
  121.         int index = (hash & 0x7FFFFFFF) % tab.length;  
  122.         // 找到“key對應的Entry(鏈表)”,然後在鏈表中找出“哈希值”和“鍵值”與key都相等的元素 
  123.         for (Entry<K,V> e = tab[index] ; e != null ; e = e.next) {  
  124.             if ((e.hash == hash) && e.key.equals(key)) {  
  125.                 return e.value;  
  126.             }  
  127.         }  
  128.         return null;  
  129.     }  
  130.  
  131.     // 調整Hashtable的長度,將長度變成原來的(2倍+1) 
  132.     // (01) 將“舊的Entry數組”賦值給一個臨時變量。 
  133.     // (02) 創建一個“新的Entry數組”,並賦值給“舊的Entry數組” 
  134.     // (03) 將“Hashtable”中的全部元素依次添加到“新的Entry數組”中 
  135.     protected void rehash() {  
  136.         int oldCapacity = table.length;  
  137.         Entry[] oldMap = table;  
  138.  
  139.         int newCapacity = oldCapacity * 2 + 1;  
  140.         Entry[] newMap = new Entry[newCapacity];  
  141.  
  142.         modCount++;  
  143.         threshold = (int)(newCapacity * loadFactor);  
  144.         table = newMap;  
  145.  
  146.         for (int i = oldCapacity ; i-- > 0 ;) {  
  147.             for (Entry<K,V> old = oldMap[i] ; old != null ; ) {  
  148.                 Entry<K,V> e = old;  
  149.                 old = old.next;  
  150.  
  151.                 int index = (e.hash & 0x7FFFFFFF) % newCapacity;  
  152.                 e.next = newMap[index];  
  153.                 newMap[index] = e;  
  154.             }  
  155.         }  
  156.     }  
  157.  
  158.     // 將“key-value”添加到Hashtable中 
  159.     public synchronized V put(K key, V value) {  
  160.         // Hashtable中不能插入value爲null的元素!!! 
  161.         if (value == null) {  
  162.             throw new NullPointerException();  
  163.         }  
  164.  
  165.         // 若“Hashtable中已存在鍵爲key的鍵值對”, 
  166.         // 則用“新的value”替換“舊的value” 
  167.         Entry tab[] = table;  
  168.         int hash = key.hashCode();  
  169.         int index = (hash & 0x7FFFFFFF) % tab.length;  
  170.         for (Entry<K,V> e = tab[index] ; e != null ; e = e.next) {  
  171.             if ((e.hash == hash) && e.key.equals(key)) {  
  172.                 V old = e.value;  
  173.                 e.value = value;  
  174.                 return old;  
  175.                 }  
  176.         }  
  177.  
  178.         // 若“Hashtable中不存在鍵爲key的鍵值對”, 
  179.         // (01) 將“修改統計數”+1 
  180.         modCount++;  
  181.         // (02) 若“Hashtable實際容量” > “閾值”(閾值=總的容量 * 加載因子) 
  182.         //  則調整Hashtable的大小 
  183.         if (count >= threshold) {  
  184.             // Rehash the table if the threshold is exceeded 
  185.             rehash();  
  186.  
  187.             tab = table;  
  188.             index = (hash & 0x7FFFFFFF) % tab.length;  
  189.         }  
  190.  
  191.         // (03) 將“Hashtable中index”位置的Entry(鏈表)保存到e中 
  192.         Entry<K,V> e = tab[index];  
  193.         // (04) 創建“新的Entry節點”,並將“新的Entry”插入“Hashtable的index位置”,並設置e爲“新的Entry”的下一個元素(即“新Entry”爲鏈表表頭)。         
  194.         tab[index] = new Entry<K,V>(hash, key, value, e);  
  195.         // (05) 將“Hashtable的實際容量”+1 
  196.         count++;  
  197.         return null;  
  198.     }  
  199.  
  200.     // 刪除Hashtable中鍵爲key的元素 
  201.     public synchronized V remove(Object key) {  
  202.         Entry tab[] = table;  
  203.         int hash = key.hashCode();  
  204.         int index = (hash & 0x7FFFFFFF) % tab.length;  
  205.         // 找到“key對應的Entry(鏈表)” 
  206.         // 然後在鏈表中找出要刪除的節點,並刪除該節點。 
  207.         for (Entry<K,V> e = tab[index], prev = null ; e != null ; prev = e, e = e.next) {  
  208.             if ((e.hash == hash) && e.key.equals(key)) {  
  209.                 modCount++;  
  210.                 if (prev != null) {  
  211.                     prev.next = e.next;  
  212.                 } else {  
  213.                     tab[index] = e.next;  
  214.                 }  
  215.                 count--;  
  216.                 V oldValue = e.value;  
  217.                 e.value = null;  
  218.                 return oldValue;  
  219.             }  
  220.         }  
  221.         return null;  
  222.     }  
  223.  
  224.     // 將“Map(t)”的中全部元素逐一添加到Hashtable中 
  225.     public synchronized void putAll(Map<? extends K, ? extends V> t) {  
  226.         for (Map.Entry<? extends K, ? extends V> e : t.entrySet())  
  227.             put(e.getKey(), e.getValue());  
  228.     }  
  229.  
  230.     // 清空Hashtable 
  231.     // 將Hashtable的table數組的值全部設爲null 
  232.     public synchronized void clear() {  
  233.         Entry tab[] = table;  
  234.         modCount++;  
  235.         for (int index = tab.length; --index >= 0; )  
  236.             tab[index] = null;  
  237.         count = 0;  
  238.     }  
  239.  
  240.     // 克隆一個Hashtable,並以Object的形式返回。 
  241.     public synchronized Object clone() {  
  242.         try {  
  243.             Hashtable<K,V> t = (Hashtable<K,V>) super.clone();  
  244.             t.table = new Entry[table.length];  
  245.             for (int i = table.length ; i-- > 0 ; ) {  
  246.                 t.table[i] = (table[i] != null)  
  247.                 ? (Entry<K,V>) table[i].clone() : null;  
  248.             }  
  249.             t.keySet = null;  
  250.             t.entrySet = null;  
  251.             t.values = null;  
  252.             t.modCount = 0;  
  253.             return t;  
  254.         } catch (CloneNotSupportedException e) {  
  255.             // this shouldn't happen, since we are Cloneable 
  256.             throw new InternalError();  
  257.         }  
  258.     }  
  259.  
  260.     public synchronized String toString() {  
  261.         int max = size() - 1;  
  262.         if (max == -1)  
  263.             return "{}";  
  264.  
  265.         StringBuilder sb = new StringBuilder();  
  266.         Iterator<Map.Entry<K,V>> it = entrySet().iterator();  
  267.  
  268.         sb.append('{');  
  269.         for (int i = 0; ; i++) {  
  270.             Map.Entry<K,V> e = it.next();  
  271.             K key = e.getKey();  
  272.             V value = e.getValue();  
  273.             sb.append(key   == this ? "(this Map)" : key.toString());  
  274.             sb.append('=');  
  275.             sb.append(value == this ? "(this Map)" : value.toString());  
  276.  
  277.             if (i == max)  
  278.                 return sb.append('}').toString();  
  279.             sb.append(", ");  
  280.         }  
  281.     }  
  282.  
  283.     // 獲取Hashtable的枚舉類對象 
  284.     // 若Hashtable的實際大小爲0,則返回“空枚舉類”對象; 
  285.     // 否則,返回正常的Enumerator的對象。(Enumerator實現了迭代器和枚舉兩個接口) 
  286.     private <T> Enumeration<T> getEnumeration(int type) {  
  287.     if (count == 0) {  
  288.         return (Enumeration<T>)emptyEnumerator;  
  289.     } else {  
  290.         return new Enumerator<T>(type, false);  
  291.     }  
  292.     }  
  293.  
  294.     // 獲取Hashtable的迭代器 
  295.     // 若Hashtable的實際大小爲0,則返回“空迭代器”對象; 
  296.     // 否則,返回正常的Enumerator的對象。(Enumerator實現了迭代器和枚舉兩個接口) 
  297.     private <T> Iterator<T> getIterator(int type) {  
  298.         if (count == 0) {  
  299.             return (Iterator<T>) emptyIterator;  
  300.         } else {  
  301.             return new Enumerator<T>(type, true);  
  302.         }  
  303.     }  
  304.  
  305.     // Hashtable的“key的集合”。它是一個Set,意味着沒有重複元素 
  306.     private transient volatile Set<K> keySet = null;  
  307.     // Hashtable的“key-value的集合”。它是一個Set,意味着沒有重複元素 
  308.     private transient volatile Set<Map.Entry<K,V>> entrySet = null;  
  309.     // Hashtable的“key-value的集合”。它是一個Collection,意味着可以有重複元素 
  310.     private transient volatile Collection<V> values = null;  
  311.  
  312.     // 返回一個被synchronizedSet封裝後的KeySet對象 
  313.     // synchronizedSet封裝的目的是對KeySet的所有方法都添加synchronized,實現多線程同步 
  314.     public Set<K> keySet() {  
  315.         if (keySet == null)  
  316.             keySet = Collections.synchronizedSet(new KeySet(), this);  
  317.         return keySet;  
  318.     }  
  319.  
  320.     // Hashtable的Key的Set集合。 
  321.     // KeySet繼承於AbstractSet,所以,KeySet中的元素沒有重複的。 
  322.     private class KeySet extends AbstractSet<K> {  
  323.         public Iterator<K> iterator() {  
  324.             return getIterator(KEYS);  
  325.         }  
  326.         public int size() {  
  327.             return count;  
  328.         }  
  329.         public boolean contains(Object o) {  
  330.             return containsKey(o);  
  331.         }  
  332.         public boolean remove(Object o) {  
  333.             return Hashtable.this.remove(o) != null;  
  334.         }  
  335.         public void clear() {  
  336.             Hashtable.this.clear();  
  337.         }  
  338.     }  
  339.  
  340.     // 返回一個被synchronizedSet封裝後的EntrySet對象 
  341.     // synchronizedSet封裝的目的是對EntrySet的所有方法都添加synchronized,實現多線程同步 
  342.     public Set<Map.Entry<K,V>> entrySet() {  
  343.         if (entrySet==null)  
  344.             entrySet = Collections.synchronizedSet(new EntrySet(), this);  
  345.         return entrySet;  
  346.     }  
  347.  
  348.     // Hashtable的Entry的Set集合。 
  349.     // EntrySet繼承於AbstractSet,所以,EntrySet中的元素沒有重複的。 
  350.     private class EntrySet extends AbstractSet<Map.Entry<K,V>> {  
  351.         public Iterator<Map.Entry<K,V>> iterator() {  
  352.             return getIterator(ENTRIES);  
  353.         }  
  354.  
  355.         public boolean add(Map.Entry<K,V> o) {  
  356.             return super.add(o);  
  357.         }  
  358.  
  359.         // 查找EntrySet中是否包含Object(0) 
  360.         // 首先,在table中找到o對應的Entry(Entry是一個單向鏈表) 
  361.         // 然後,查找Entry鏈表中是否存在Object 
  362.         public boolean contains(Object o) {  
  363.             if (!(o instanceof Map.Entry))  
  364.                 return false;  
  365.             Map.Entry entry = (Map.Entry)o;  
  366.             Object key = entry.getKey();  
  367.             Entry[] tab = table;  
  368.             int hash = key.hashCode();  
  369.             int index = (hash & 0x7FFFFFFF) % tab.length;  
  370.  
  371.             for (Entry e = tab[index]; e != null; e = e.next)  
  372.                 if (e.hash==hash && e.equals(entry))  
  373.                     return true;  
  374.             return false;  
  375.         }  
  376.  
  377.         // 刪除元素Object(0) 
  378.         // 首先,在table中找到o對應的Entry(Entry是一個單向鏈表) 
  379.         // 然後,刪除鏈表中的元素Object 
  380.         public boolean remove(Object o) {  
  381.             if (!(o instanceof Map.Entry))  
  382.                 return false;  
  383.             Map.Entry<K,V> entry = (Map.Entry<K,V>) o;  
  384.             K key = entry.getKey();  
  385.             Entry[] tab = table;  
  386.             int hash = key.hashCode();  
  387.             int index = (hash & 0x7FFFFFFF) % tab.length;  
  388.  
  389.             for (Entry<K,V> e = tab[index], prev = null; e != null;  
  390.                  prev = e, e = e.next) {  
  391.                 if (e.hash==hash && e.equals(entry)) {  
  392.                     modCount++;  
  393.                     if (prev != null)  
  394.                         prev.next = e.next;  
  395.                     else 
  396.                         tab[index] = e.next;  
  397.  
  398.                     count--;  
  399.                     e.value = null;  
  400.                     return true;  
  401.                 }  
  402.             }  
  403.             return false;  
  404.         }  
  405.  
  406.         public int size() {  
  407.             return count;  
  408.         }  
  409.  
  410.         public void clear() {  
  411.             Hashtable.this.clear();  
  412.         }  
  413.     }  
  414.  
  415.     // 返回一個被synchronizedCollection封裝後的ValueCollection對象 
  416.     // synchronizedCollection封裝的目的是對ValueCollection的所有方法都添加synchronized,實現多線程同步 
  417.     public Collection<V> values() {  
  418.     if (values==null)  
  419.         values = Collections.synchronizedCollection(new ValueCollection(),  
  420.                                                         this);  
  421.         return values;  
  422.     }  
  423.  
  424.     // Hashtable的value的Collection集合。 
  425.     // ValueCollection繼承於AbstractCollection,所以,ValueCollection中的元素可以重複的。 
  426.     private class ValueCollection extends AbstractCollection<V> {  
  427.         public Iterator<V> iterator() {  
  428.         return getIterator(VALUES);  
  429.         }  
  430.         public int size() {  
  431.             return count;  
  432.         }  
  433.         public boolean contains(Object o) {  
  434.             return containsValue(o);  
  435.         }  
  436.         public void clear() {  
  437.             Hashtable.this.clear();  
  438.         }  
  439.     }  
  440.  
  441.     // 重新equals()函數 
  442.     // 若兩個Hashtable的所有key-value鍵值對都相等,則判斷它們兩個相等 
  443.     public synchronized boolean equals(Object o) {  
  444.         if (o == this)  
  445.             return true;  
  446.  
  447.         if (!(o instanceof Map))  
  448.             return false;  
  449.         Map<K,V> t = (Map<K,V>) o;  
  450.         if (t.size() != size())  
  451.             return false;  
  452.  
  453.         try {  
  454.             // 通過迭代器依次取出當前Hashtable的key-value鍵值對 
  455.             // 並判斷該鍵值對,存在於Hashtable(o)中。 
  456.             // 若不存在,則立即返回false;否則,遍歷完“當前Hashtable”並返回true。 
  457.             Iterator<Map.Entry<K,V>> i = entrySet().iterator();  
  458.             while (i.hasNext()) {  
  459.                 Map.Entry<K,V> e = i.next();  
  460.                 K key = e.getKey();  
  461.                 V value = e.getValue();  
  462.                 if (value == null) {  
  463.                     if (!(t.get(key)==null && t.containsKey(key)))  
  464.                         return false;  
  465.                 } else {  
  466.                     if (!value.equals(t.get(key)))  
  467.                         return false;  
  468.                 }  
  469.             }  
  470.         } catch (ClassCastException unused)   {  
  471.             return false;  
  472.         } catch (NullPointerException unused) {  
  473.             return false;  
  474.         }  
  475.  
  476.         return true;  
  477.     }  
  478.  
  479.     // 計算Hashtable的哈希值 
  480.     // 若 Hashtable的實際大小爲0 或者 加載因子<0,則返回0。 
  481.     // 否則,返回“Hashtable中的每個Entry的key和value的異或值 的總和”。 
  482.     public synchronized int hashCode() {  
  483.         int h = 0;  
  484.         if (count == 0 || loadFactor < 0)  
  485.             return h;  // Returns zero 
  486.  
  487.         loadFactor = -loadFactor;  // Mark hashCode computation in progress 
  488.         Entry[] tab = table;  
  489.         for (int i = 0; i < tab.length; i++)  
  490.             for (Entry e = tab[i]; e != null; e = e.next)  
  491.                 h += e.key.hashCode() ^ e.value.hashCode();  
  492.         loadFactor = -loadFactor;  // Mark hashCode computation complete 
  493.  
  494.         return h;  
  495.     }  
  496.  
  497.     // java.io.Serializable的寫入函數 
  498.     // 將Hashtable的“總的容量,實際容量,所有的Entry”都寫入到輸出流中 
  499.     private synchronized void writeObject(java.io.ObjectOutputStream s)  
  500.         throws IOException  
  501.     {  
  502.         // Write out the length, threshold, loadfactor 
  503.         s.defaultWriteObject();  
  504.  
  505.         // Write out length, count of elements and then the key/value objects 
  506.         s.writeInt(table.length);  
  507.         s.writeInt(count);  
  508.         for (int index = table.length-1; index >= 0; index--) {  
  509.             Entry entry = table[index];  
  510.  
  511.             while (entry != null) {  
  512.             s.writeObject(entry.key);  
  513.             s.writeObject(entry.value);  
  514.             entry = entry.next;  
  515.             }  
  516.         }  
  517.     }  
  518.  
  519.     // java.io.Serializable的讀取函數:根據寫入方式讀出 
  520.     // 將Hashtable的“總的容量,實際容量,所有的Entry”依次讀出 
  521.     private void readObject(java.io.ObjectInputStream s)  
  522.          throws IOException, ClassNotFoundException  
  523.     {  
  524.         // Read in the length, threshold, and loadfactor 
  525.         s.defaultReadObject();  
  526.  
  527.         // Read the original length of the array and number of elements 
  528.         int origlength = s.readInt();  
  529.         int elements = s.readInt();  
  530.  
  531.         // Compute new size with a bit of room 5% to grow but 
  532.         // no larger than the original size.  Make the length 
  533.         // odd if it's large enough, this helps distribute the entries. 
  534.         // Guard against the length ending up zero, that's not valid. 
  535.         int length = (int)(elements * loadFactor) + (elements / 20) + 3;  
  536.         if (length > elements && (length & 1) == 0)  
  537.             length--;  
  538.         if (origlength > 0 && length > origlength)  
  539.             length = origlength;  
  540.  
  541.         Entry[] table = new Entry[length];  
  542.         count = 0;  
  543.  
  544.         // Read the number of elements and then all the key/value objects 
  545.         for (; elements > 0; elements--) {  
  546.             K key = (K)s.readObject();  
  547.             V value = (V)s.readObject();  
  548.                 // synch could be eliminated for performance 
  549.                 reconstitutionPut(table, key, value);  
  550.         }  
  551.         this.table = table;  
  552.     }  
  553.  
  554.     private void reconstitutionPut(Entry[] tab, K key, V value)  
  555.         throws StreamCorruptedException  
  556.     {  
  557.         if (value == null) {  
  558.             throw new java.io.StreamCorruptedException();  
  559.         }  
  560.         // Makes sure the key is not already in the hashtable. 
  561.         // This should not happen in deserialized version. 
  562.         int hash = key.hashCode();  
  563.         int index = (hash & 0x7FFFFFFF) % tab.length;  
  564.         for (Entry<K,V> e = tab[index] ; e != null ; e = e.next) {  
  565.             if ((e.hash == hash) && e.key.equals(key)) {  
  566.                 throw new java.io.StreamCorruptedException();  
  567.             }  
  568.         }  
  569.         // Creates the new entry. 
  570.         Entry<K,V> e = tab[index];  
  571.         tab[index] = new Entry<K,V>(hash, key, value, e);  
  572.         count++;  
  573.     }  
  574.  
  575.     // Hashtable的Entry節點,它本質上是一個單向鏈表。 
  576.     // 也因此,我們才能推斷出Hashtable是由拉鍊法實現的散列表 
  577.     private static class Entry<K,V> implements Map.Entry<K,V> {  
  578.         // 哈希值 
  579.         int hash;  
  580.         K key;  
  581.         V value;  
  582.         // 指向的下一個Entry,即鏈表的下一個節點 
  583.         Entry<K,V> next;  
  584.  
  585.         // 構造函數 
  586.         protected Entry(int hash, K key, V value, Entry<K,V> next) {  
  587.             this.hash = hash;  
  588.             this.key = key;  
  589.             this.value = value;  
  590.             this.next = next;  
  591.         }  
  592.  
  593.         protected Object clone() {  
  594.             return new Entry<K,V>(hash, key, value,  
  595.                   (next==null ? null : (Entry<K,V>) next.clone()));  
  596.         }  
  597.  
  598.         public K getKey() {  
  599.             return key;  
  600.         }  
  601.  
  602.         public V getValue() {  
  603.             return value;  
  604.         }  
  605.  
  606.         // 設置value。若value是null,則拋出異常。 
  607.         public V setValue(V value) {  
  608.             if (value == null)  
  609.                 throw new NullPointerException();  
  610.  
  611.             V oldValue = this.value;  
  612.             this.value = value;  
  613.             return oldValue;  
  614.         }  
  615.  
  616.         // 覆蓋equals()方法,判斷兩個Entry是否相等。 
  617.         // 若兩個Entry的key和value都相等,則認爲它們相等。 
  618.         public boolean equals(Object o) {  
  619.             if (!(o instanceof Map.Entry))  
  620.                 return false;  
  621.             Map.Entry e = (Map.Entry)o;  
  622.  
  623.             return (key==null ? e.getKey()==null : key.equals(e.getKey())) &&  
  624.                (value==null ? e.getValue()==null : value.equals(e.getValue()));  
  625.         }  
  626.  
  627.         public int hashCode() {  
  628.             return hash ^ (value==null ? 0 : value.hashCode());  
  629.         }  
  630.  
  631.         public String toString() {  
  632.             return key.toString()+"="+value.toString();  
  633.         }  
  634.     }  
  635.  
  636.     private static final int KEYS = 0;  
  637.     private static final int VALUES = 1;  
  638.     private static final int ENTRIES = 2;  
  639.  
  640.     // Enumerator的作用是提供了“通過elements()遍歷Hashtable的接口” 和 “通過entrySet()遍歷Hashtable的接口”。因爲,它同時實現了 “Enumerator接口”和“Iterator接口”。 
  641.     private class Enumerator<T> implements Enumeration<T>, Iterator<T> {  
  642.         // 指向Hashtable的table 
  643.         Entry[] table = Hashtable.this.table;  
  644.         // Hashtable的總的大小 
  645.         int index = table.length;  
  646.         Entry<K,V> entry = null;  
  647.         Entry<K,V> lastReturned = null;  
  648.         int type;  
  649.  
  650.         // Enumerator是 “迭代器(Iterator)” 還是 “枚舉類(Enumeration)”的標誌 
  651.         // iterator爲true,表示它是迭代器;否則,是枚舉類。 
  652.         boolean iterator;  
  653.  
  654.         // 在將Enumerator當作迭代器使用時會用到,用來實現fail-fast機制。 
  655.         protected int expectedModCount = modCount;  
  656.  
  657.         Enumerator(int type, boolean iterator) {  
  658.             this.type = type;  
  659.             this.iterator = iterator;  
  660.         }  
  661.  
  662.         // 從遍歷table的數組的末尾向前查找,直到找到不爲null的Entry。 
  663.         public boolean hasMoreElements() {  
  664.             Entry<K,V> e = entry;  
  665.             int i = index;  
  666.             Entry[] t = table;  
  667.             /* Use locals for faster loop iteration */ 
  668.             while (e == null && i > 0) {  
  669.                 e = t[--i];  
  670.             }  
  671.             entry = e;  
  672.             index = i;  
  673.             return e != null;  
  674.         }  
  675.  
  676.         // 獲取下一個元素 
  677.         // 注意:從hasMoreElements() 和nextElement() 可以看出“Hashtable的elements()遍歷方式” 
  678.         // 首先,從後向前的遍歷table數組。table數組的每個節點都是一個單向鏈表(Entry)。 
  679.         // 然後,依次向後遍歷單向鏈表Entry。 
  680.         public T nextElement() {  
  681.             Entry<K,V> et = entry;  
  682.             int i = index;  
  683.             Entry[] t = table;  
  684.             /* Use locals for faster loop iteration */ 
  685.             while (et == null && i > 0) {  
  686.                 et = t[--i];  
  687.             }  
  688.             entry = et;  
  689.             index = i;  
  690.             if (et != null) {  
  691.                 Entry<K,V> e = lastReturned = entry;  
  692.                 entry = e.next;  
  693.                 return type == KEYS ? (T)e.key : (type == VALUES ? (T)e.value : (T)e);  
  694.             }  
  695.             throw new NoSuchElementException("Hashtable Enumerator");  
  696.         }  
  697.  
  698.         // 迭代器Iterator的判斷是否存在下一個元素 
  699.         // 實際上,它是調用的hasMoreElements() 
  700.         public boolean hasNext() {  
  701.             return hasMoreElements();  
  702.         }  
  703.  
  704.         // 迭代器獲取下一個元素 
  705.         // 實際上,它是調用的nextElement() 
  706.         public T next() {  
  707.             if (modCount != expectedModCount)  
  708.                 throw new ConcurrentModificationException();  
  709.             return nextElement();  
  710.         }  
  711.  
  712.         // 迭代器的remove()接口。 
  713.         // 首先,它在table數組中找出要刪除元素所在的Entry, 
  714.         // 然後,刪除單向鏈表Entry中的元素。 
  715.         public void remove() {  
  716.             if (!iterator)  
  717.                 throw new UnsupportedOperationException();  
  718.             if (lastReturned == null)  
  719.                 throw new IllegalStateException("Hashtable Enumerator");  
  720.             if (modCount != expectedModCount)  
  721.                 throw new ConcurrentModificationException();  
  722.  
  723.             synchronized(Hashtable.this) {  
  724.                 Entry[] tab = Hashtable.this.table;  
  725.                 int index = (lastReturned.hash & 0x7FFFFFFF) % tab.length;  
  726.  
  727.                 for (Entry<K,V> e = tab[index], prev = null; e != null;  
  728.                      prev = e, e = e.next) {  
  729.                     if (e == lastReturned) {  
  730.                         modCount++;  
  731.                         expectedModCount++;  
  732.                         if (prev == null)  
  733.                             tab[index] = e.next;  
  734.                         else 
  735.                             prev.next = e.next;  
  736.                         count--;  
  737.                         lastReturned = null;  
  738.                         return;  
  739.                     }  
  740.                 }  
  741.                 throw new ConcurrentModificationException();  
  742.             }  
  743.         }  
  744.     }  
  745.  
  746.  
  747.     private static Enumeration emptyEnumerator = new EmptyEnumerator();  
  748.     private static Iterator emptyIterator = new EmptyIterator();  
  749.  
  750.     // 空枚舉類 
  751.     // 當Hashtable的實際大小爲0;此時,又要通過Enumeration遍歷Hashtable時,返回的是“空枚舉類”的對象。 
  752.     private static class EmptyEnumerator implements Enumeration<Object> {  
  753.  
  754.         EmptyEnumerator() {  
  755.         }  
  756.  
  757.         // 空枚舉類的hasMoreElements() 始終返回false 
  758.         public boolean hasMoreElements() {  
  759.             return false;  
  760.         }  
  761.  
  762.         // 空枚舉類的nextElement() 拋出異常 
  763.         public Object nextElement() {  
  764.             throw new NoSuchElementException("Hashtable Enumerator");  
  765.         }  
  766.     }  
  767.  
  768.  
  769.     // 空迭代器 
  770.     // 當Hashtable的實際大小爲0;此時,又要通過迭代器遍歷Hashtable時,返回的是“空迭代器”的對象。 
  771.     private static class EmptyIterator implements Iterator<Object> {  
  772.  
  773.         EmptyIterator() {  
  774.         }  
  775.  
  776.         public boolean hasNext() {  
  777.             return false;  
  778.         }  
  779.  
  780.         public Object next() {  
  781.             throw new NoSuchElementException("Hashtable Iterator");  
  782.         }  
  783.  
  784.         public void remove() {  
  785.             throw new IllegalStateException("Hashtable Iterator");  
  786.         }  
  787.  
  788.     }  
和Hashmap一樣,Hashtable也是一個散列表,它也是通過“拉鍊法”解決哈希衝突的。

 Entry 實際上就是一個單向鏈表。這也是爲什麼我們說Hashtable是通過拉鍊法解決哈希衝突的。
Entry 實現了Map.Entry 接口,即實現getKey(), getValue(), setValue(V value), equals(Object o), hashCode()這些函數。這些都是基本的讀取/修改key、value值的函數。

Hashtable的主要對外接口

2.3.1 clear()

clear() 的作用是清空Hashtable。它是將Hashtable的table數組的值全部設爲null

  1. public synchronized void clear() {  
  2.     Entry tab[] = table;  
  3.     modCount++;  
  4.     for (int index = tab.length; --index >= 0; )  
  5.         tab[index] = null;  
  6.     count = 0;  

2.3.2 contains() 和 containsValue()

contains() 和 containsValue() 的作用都是判斷Hashtable是否包含“值(value)”

  1. public boolean containsValue(Object value) {  
  2.     return contains(value);  
  3. }  
  4.  
  5. public synchronized boolean contains(Object value) {  
  6.     // Hashtable中“鍵值對”的value不能是null,  
  7.     // 若是null的話,拋出異常!  
  8.     if (value == null) {  
  9.         throw new NullPointerException();  
  10.     }  
  11.  
  12.     // 從後向前遍歷table數組中的元素(Entry)  
  13.     // 對於每個Entry(單向鏈表),逐個遍歷,判斷節點的值是否等於value  
  14.     Entry tab[] = table;  
  15.     for (int i = tab.length ; i-- > 0 ;) {  
  16.         for (Entry<K,V> e = tab[i] ; e != null ; e = e.next) {  
  17.             if (e.value.equals(value)) {  
  18.                 return true;  
  19.             }  
  20.         }  
  21.     }  
  22.     return false;  

2.3.3 containsKey()

containsKey() 的作用是判斷Hashtable是否包含key

  1. public synchronized boolean containsKey(Object key) {  
  2.     Entry tab[] = table;  
  3.     int hash = key.hashCode();  
  4.     // 計算索引值,  
  5.     // % tab.length 的目的是防止數據越界  
  6.     int index = (hash & 0x7FFFFFFF) % tab.length;  
  7.     // 找到“key對應的Entry(鏈表)”,然後在鏈表中找出“哈希值”和“鍵值”與key都相等的元素  
  8.     for (Entry<K,V> e = tab[index] ; e != null ; e = e.next) {  
  9.         if ((e.hash == hash) && e.key.equals(key)) {  
  10.             return true;  
  11.         }  
  12.     }  
  13.     return false;  

2.3.4 elements()

elements() 的作用是返回“所有value”的枚舉對象

  1. public synchronized Enumeration<V> elements() {  
  2.     return this.<V>getEnumeration(VALUES);  
  3. }  
  4.  
  5. // 獲取Hashtable的枚舉類對象  
  6. private <T> Enumeration<T> getEnumeration(int type) {  
  7.     if (count == 0) {  
  8.         return (Enumeration<T>)emptyEnumerator;  
  9.     } else {  
  10.         return new Enumerator<T>(type, false);  
  11.     }  

我們可以看出:
(01) 若Hashtable的實際大小爲0,則返回“空枚舉類”對象emptyEnumerator;
(02) 否則,返回正常的Enumerator的對象。(Enumerator實現了迭代器和枚舉兩個接口)

我們先看看emptyEnumerator對象是如何實現的

  1. private static Enumeration emptyEnumerator = new EmptyEnumerator();  
  2.  
  3. // 空枚舉類  
  4. // 當Hashtable的實際大小爲0;此時,又要通過Enumeration遍歷Hashtable時,返回的是“空枚舉類”的對象。  
  5. private static class EmptyEnumerator implements Enumeration<Object> {  
  6.  
  7.     EmptyEnumerator() {  
  8.     }  
  9.  
  10.     // 空枚舉類的hasMoreElements() 始終返回false  
  11.     public boolean hasMoreElements() {  
  12.         return false;  
  13.     }  
  14.  
  15.     // 空枚舉類的nextElement() 拋出異常  
  16.     public Object nextElement() {  
  17.         throw new NoSuchElementException("Hashtable Enumerator");  
  18.     }  

我們在來看看Enumeration類

Enumerator的作用是提供了“通過elements()遍歷Hashtable的接口” 和 “通過entrySet()遍歷Hashtable的接口”。因爲,它同時實現了 “Enumerator接口”和“Iterator接口”。

  1. private class Enumerator<T> implements Enumeration<T>, Iterator<T> {  
  2.     // 指向Hashtable的table  
  3.     Entry[] table = Hashtable.this.table;  
  4.     // Hashtable的總的大小  
  5.     int index = table.length;  
  6.     Entry<K,V> entry = null;  
  7.     Entry<K,V> lastReturned = null;  
  8.     int type;  
  9.  
  10.     // Enumerator是 “迭代器(Iterator)” 還是 “枚舉類(Enumeration)”的標誌  
  11.     // iterator爲true,表示它是迭代器;否則,是枚舉類。  
  12.     boolean iterator;  
  13.  
  14.     // 在將Enumerator當作迭代器使用時會用到,用來實現fail-fast機制。  
  15.     protected int expectedModCount = modCount;  
  16.  
  17.     Enumerator(int type, boolean iterator) {  
  18.         this.type = type;  
  19.         this.iterator = iterator;  
  20.     }  
  21.  
  22.     // 從遍歷table的數組的末尾向前查找,直到找到不爲null的Entry。  
  23.     public boolean hasMoreElements() {  
  24.         Entry<K,V> e = entry;  
  25.         int i = index;  
  26.         Entry[] t = table;  
  27.         /* Use locals for faster loop iteration */ 
  28.         while (e == null && i > 0) {  
  29.             e = t[--i];  
  30.         }  
  31.         entry = e;  
  32.         index = i;  
  33.         return e != null;  
  34.     }  
  35.  
  36.     // 獲取下一個元素  
  37.     // 注意:從hasMoreElements() 和nextElement() 可以看出“Hashtable的elements()遍歷方式”  
  38.     // 首先,從後向前的遍歷table數組。table數組的每個節點都是一個單向鏈表(Entry)。  
  39.     // 然後,依次向後遍歷單向鏈表Entry。  
  40.     public T nextElement() {  
  41.         Entry<K,V> et = entry;  
  42.         int i = index;  
  43.         Entry[] t = table;  
  44.         /* Use locals for faster loop iteration */ 
  45.         while (et == null && i > 0) {  
  46.             et = t[--i];  
  47.         }  
  48.         entry = et;  
  49.         index = i;  
  50.         if (et != null) {  
  51.             Entry<K,V> e = lastReturned = entry;  
  52.             entry = e.next;  
  53.             return type == KEYS ? (T)e.key : (type == VALUES ? (T)e.value : (T)e);  
  54.         }  
  55.         throw new NoSuchElementException("Hashtable Enumerator");  
  56.     }  
  57.  
  58.     // 迭代器Iterator的判斷是否存在下一個元素  
  59.     // 實際上,它是調用的hasMoreElements()  
  60.     public boolean hasNext() {  
  61.         return hasMoreElements();  
  62.     }  
  63.  
  64.     // 迭代器獲取下一個元素  
  65.     // 實際上,它是調用的nextElement()  
  66.     public T next() {  
  67.         if (modCount != expectedModCount)  
  68.             throw new ConcurrentModificationException();  
  69.         return nextElement();  
  70.     }  
  71.  
  72.     // 迭代器的remove()接口。  
  73.     // 首先,它在table數組中找出要刪除元素所在的Entry,  
  74.     // 然後,刪除單向鏈表Entry中的元素。  
  75.     public void remove() {  
  76.         if (!iterator)  
  77.             throw new UnsupportedOperationException();  
  78.         if (lastReturned == null)  
  79.             throw new IllegalStateException("Hashtable Enumerator");  
  80.         if (modCount != expectedModCount)  
  81.             throw new ConcurrentModificationException();  
  82.  
  83.         synchronized(Hashtable.this) {  
  84.             Entry[] tab = Hashtable.this.table;  
  85.             int index = (lastReturned.hash & 0x7FFFFFFF) % tab.length;  
  86.  
  87.             for (Entry<K,V> e = tab[index], prev = null; e != null;  
  88.                  prev = e, e = e.next) {  
  89.                 if (e == lastReturned) {  
  90.                     modCount++;  
  91.                     expectedModCount++;  
  92.                     if (prev == null)  
  93.                         tab[index] = e.next;  
  94.                     else 
  95.                         prev.next = e.next;  
  96.                     count--;  
  97.                     lastReturned = null;  
  98.                     return;  
  99.                 }  
  100.             }  
  101.             throw new ConcurrentModificationException();  
  102.         }  
  103.     }  

entrySet(), keySet(), keys(), values()的實現方法和elements()差不多,而且源碼中已經明確的給出了註釋。這裏就不再做過多說明了。

2.3.5 get()

get() 的作用就是獲取key對應的value,沒有的話返回null

  1. public synchronized V get(Object key) {  
  2.     Entry tab[] = table;  
  3.     int hash = key.hashCode();  
  4.     // 計算索引值,  
  5.     int index = (hash & 0x7FFFFFFF) % tab.length;  
  6.     // 找到“key對應的Entry(鏈表)”,然後在鏈表中找出“哈希值”和“鍵值”與key都相等的元素  
  7.     for (Entry<K,V> e = tab[index] ; e != null ; e = e.next) {  
  8.         if ((e.hash == hash) && e.key.equals(key)) {  
  9.             return e.value;  
  10.         }  
  11.     }  
  12.     return null;  

2.3.6 put()

put() 的作用是對外提供接口,讓Hashtable對象可以通過put()將“key-value”添加到Hashtable中。

  1. public synchronized V put(K key, V value) {  
  2.     // Hashtable中不能插入value爲null的元素!!!  
  3.     if (value == null) {  
  4.         throw new NullPointerException();  
  5.     }  
  6.  
  7.     // 若“Hashtable中已存在鍵爲key的鍵值對”,  
  8.     // 則用“新的value”替換“舊的value”  
  9.     Entry tab[] = table;  
  10.     int hash = key.hashCode();  
  11.     int index = (hash & 0x7FFFFFFF) % tab.length;  
  12.     for (Entry<K,V> e = tab[index] ; e != null ; e = e.next) {  
  13.         if ((e.hash == hash) && e.key.equals(key)) {  
  14.             V old = e.value;  
  15.             e.value = value;  
  16.             return old;  
  17.             }  
  18.     }  
  19.  
  20.     // 若“Hashtable中不存在鍵爲key的鍵值對”,  
  21.     // (01) 將“修改統計數”+1  
  22.     modCount++;  
  23.     // (02) 若“Hashtable實際容量” > “閾值”(閾值=總的容量 * 加載因子)  
  24.     //  則調整Hashtable的大小  
  25.     if (count >= threshold) {  
  26.         // Rehash the table if the threshold is exceeded  
  27.         rehash();  
  28.  
  29.         tab = table;  
  30.         index = (hash & 0x7FFFFFFF) % tab.length;  
  31.     }  
  32.  
  33.     // (03) 將“Hashtable中index”位置的Entry(鏈表)保存到e中  
  34.     Entry<K,V> e = tab[index];  
  35.     // (04) 創建“新的Entry節點”,並將“新的Entry”插入“Hashtable的index位置”,並設置e爲“新的Entry”的下一個元素(即“新Entry”爲鏈表表頭)。          
  36.     tab[index] = new Entry<K,V>(hash, key, value, e);  
  37.     // (05) 將“Hashtable的實際容量”+1  
  38.     count++;  
  39.     return null;  


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章