HashTable源码分析

来源:互联网 发布:怎样下载excel2003软件 编辑:程序博客网 时间:2024/06/01 07:29

转自:

和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;  


0 0
原创粉丝点击