JDK源码阅读--Hashtable

 

public class Hashtable<K,V>
extends Dictionary<K,V>
implements Map<K,V>, Cloneable, java.io.Serializable {


Hashtable的默认初始容量是11,加载因子是0.75f。通过synchronized方法保证线程安全。
实现结构与HashMap基本一致。Hashtable的键和值都不能为空。

Hashtable的构造函数:
 1     /**
 2      * 使用指定的初始容量和装载因子构造一个空的Hashtable.
 3      *
 4      * @param      initialCapacity   hashtable的初始容量
 5      * @param      loadFactor        hashtable的装载因子
 6      * @exception  IllegalArgumentException  如果初始容量小于0,或装载因子是负数,则抛出IllegalArgumentException异常
 7      */
 8     public Hashtable(int initialCapacity, float loadFactor) {
 9         if (initialCapacity < 0)
10             throw new IllegalArgumentException("Illegal Capacity: "+
11                                                initialCapacity);
12         if (loadFactor <= 0 || Float.isNaN(loadFactor))
13             throw new IllegalArgumentException("Illegal Load: "+loadFactor);
14 
15         if (initialCapacity==0)
16             initialCapacity = 1;
17         this.loadFactor = loadFactor;
18         table = new Entry<?,?>[initialCapacity];
19         threshold = (int)Math.min(initialCapacity * loadFactor, MAX_ARRAY_SIZE + 1);
20     }
21 
22     /**
23      * Constructs a new, empty hashtable with the specified initial capacity
24      * and default load factor (0.75).
25      *
26      * @param     initialCapacity   the initial capacity of the hashtable.
27      * @exception IllegalArgumentException if the initial capacity is less
28      *              than zero.
29      */
30     public Hashtable(int initialCapacity) {
31         this(initialCapacity, 0.75f);
32     }
33 
34     /**
35      * Constructs a new, empty hashtable with a default initial capacity (11)
36      * and load factor (0.75).
37      */
38     public Hashtable() {
39         this(11, 0.75f);
40     }
41 
42     /**
43      * Constructs a new hashtable with the same mappings as the given
44      * Map.  The hashtable is created with an initial capacity sufficient to
45      * hold the mappings in the given Map and a default load factor (0.75).
46      *
47      * @param t the map whose mappings are to be placed in this map.
48      * @throws NullPointerException if the specified map is null.
49      * @since   1.2
50      */
51     public Hashtable(Map<? extends K, ? extends V> t) {
52         this(Math.max(2*t.size(), 11), 0.75f);
53         putAll(t);
54     }

 

posted @ 2019-03-14 16:30  以前、以后  阅读(189)  评论(0编辑  收藏  举报