天天看點

第五篇:JAVA集合之Hashtable源碼剖析Hashtable簡介HashTable源碼剖析 幾點總結

Hashtable簡介

    Hashtable同樣是基于哈希表實作的,同樣每個元素是一個key-value對,其内部也是通過單連結清單解決沖突問題,容量不足(超過了閥值)時,同樣會自動增長。

    Hashtable也是JDK1.0引入的類,是線程安全的,能用于多線程環境中。

    Hashtable同樣實作了Serializable接口,它支援序列化,實作了Cloneable接口,能被克隆。

HashTable源碼剖析

    Hashtable的源碼的很多實作都與HashMap差不多,源碼如下(加入了比較詳細的注釋):

[java]  view plain  copy

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

幾點總結

    針對Hashtable,我們同樣給出幾點比較重要的總結,但要結合與HashMap的比較來總結。

    1、二者的存儲結構和解決沖突的方法都是相同的。

    2、HashTable在不指定容量的情況下的預設容量為11,而HashMap為16,Hashtable不要求底層數組的容量一定要為2的整數次幂,而HashMap則要求一定為2的整數次幂。

    3、Hashtable中key和value都不允許為null,而HashMap中key和value都允許為null(key隻能有一個為null,而value則可以有多個為null)。但是如果在Hashtable中有類似put(null,null)的操作,編譯同樣可以通過,因為key和value都是Object類型,但運作時會抛出NullPointerException異常,這是JDK的規範規定的。我們來看下ContainsKey方法和ContainsValue的源碼:

[java]  view plain  copy

  1. // 判斷Hashtable是否包含“值(value)”    
  2.  public synchronized boolean contains(Object value) {    
  3.      //注意,Hashtable中的value不能是null,    
  4.      // 若是null的話,抛出異常!    
  5.      if (value == null) {    
  6.          throw new NullPointerException();    
  7.      }    
  8.      // 從後向前周遊table數組中的元素(Entry)    
  9.      // 對于每個Entry(單向連結清單),逐個周遊,判斷節點的值是否等于value    
  10.      Entry tab[] = table;    
  11.      for (int i = tab.length ; i-- > 0 ;) {    
  12.          for (Entry<K,V> e = tab[i] ; e != null ; e = e.next) {    
  13.              if (e.value.equals(value)) {    
  14.                  return true;    
  15.              }    
  16.          }    
  17.      }    
  18.      return false;    
  19.  }    
  20.  public boolean containsValue(Object value) {    
  21.      return contains(value);    
  22.  }    
  23.  // 判斷Hashtable是否包含key    
  24.  public synchronized boolean containsKey(Object key) {    
  25.      Entry tab[] = table;    
  26. /計算hash值,直接用key的hashCode代替  
  27.      int hash = key.hashCode();      
  28.      // 計算在數組中的索引值   
  29.      int index = (hash & 0x7FFFFFFF) % tab.length;    
  30.      // 找到“key對應的Entry(連結清單)”,然後在連結清單中找出“哈希值”和“鍵值”與key都相等的元素    
  31.      for (Entry<K,V> e = tab[index] ; e != null ; e = e.next) {    
  32.          if ((e.hash == hash) && e.key.equals(key)) {    
  33.              return true;    
  34.          }    
  35.      }    
  36.      return false;    
  37.  }    

    很明顯,如果value為null,會直接抛出NullPointerException異常,但源碼中并沒有對key是否為null判斷,有點小不解!不過NullPointerException屬于RuntimeException異常,是可以由JVM自動抛出的,也許對key的值在JVM中有所限制吧。

    4、Hashtable擴容時,将容量變為原來的2倍加1,而HashMap擴容時,将容量變為原來的2倍。

    5、Hashtable計算hash值,直接用key的hashCode(),而HashMap重新計算了key的hash值,Hashtable在求hash值對應的位置索引時,用取模運算,而HashMap在求位置索引時,則用與運算,且這裡一般先用hash&0x7FFFFFFF後,再對length取模,&0x7FFFFFFF的目的是為了将負的hash值轉化為正值,因為hash值有可能為負數,而&0x7FFFFFFF後,隻有符号外改變,而後面的位都不變。