Java集合详解(五):Hashtable原理解析
概述
  本文是基于jdk8_271版本进行分析的。
  Hashtable与HashMap一样,是一个存储key-value的双列集合。底层是基于数组+链表实现的,没有红黑树结构。Hashtable默认初始化容量为11,Hashtable也会动态扩容,与HashMap不同的是,每次扩容的容量是原容量2倍+1。Hashtable的key和value都不允许为null。Hashtable在方法上都加了synchronized同步锁。所以Hashtable是线程安全的,同时Hashtable的效率也相对较低。
数据结构

- 实现继承关系
1 public class Hashtable<K,V>
2 extends Dictionary<K,V>
3 implements Map<K,V>, Cloneable, java.io.Serializable
- Dictionary:
- Map:
- Cloneable:
- Serializable:
- 成员变量
1 // 存放hash表数据
2 private transient Entry<?,?>[] table;
3
4 // 元素数量
5 private transient int count;
6
7 // 阈值。元素数量达到该值,进行扩容
8 private int threshold;
9
10 // 加载因子,默认是0.75
11 private float loadFactor;
12
13 // 修改次数
14 private transient int modCount = 0;
- 构造函数
Hashtable默认初始化容量为11,默认加载因子的值为0.75(与HashMap一样)。选择0.75作为默认的加载因子,完全是时间和空间成本上寻求的一种折中选择。加载因子过高虽然减少了空间开销,但同时也增加了查询成本;加载因子过低虽然可以减少查询时间成本,但是空间利用率很低。
Hashtable初始化容量值使用传入的值(0除外),不会重新计算(HashMap需要重新计算,使得容量大小为2的指数次幂)。在构造方法创建对象时,会直接初始化数组,没有采用懒加载的方式。
 1     public Hashtable(int initialCapacity, float loadFactor) {
 2         if (initialCapacity < 0)
 3             throw new IllegalArgumentException("Illegal Capacity: "+
 4                                                initialCapacity);
 5         if (loadFactor <= 0 || Float.isNaN(loadFactor))
 6             throw new IllegalArgumentException("Illegal Load: "+loadFactor);
 7         // 如果初始化容量传入的是0,则默认使用1
 8         if (initialCapacity==0)
 9             initialCapacity = 1;
10         this.loadFactor = loadFactor;
11         table = new Entry<?,?>[initialCapacity];
12         // 计算阈值。预计的阈值为初始化容量*加载因子,预计的阈值如果大于MAX_ARRAY_SIZE + 1,则实际阈值设置为MAX_ARRAY_SIZE + 1
13         threshold = (int)Math.min(initialCapacity * loadFactor, MAX_ARRAY_SIZE + 1);
14     }
15
16     public Hashtable(int initialCapacity) {
17         // 传入初始化容量,加载因子使用默认值0.75。初始化容量传入的是多少就初始化多大(0除外;传入的如果0,默认使用1),不需要再重新计算
18         this(initialCapacity, 0.75f);
19     }
20
21     public Hashtable() {
22         // 默认初始化容量11,默认加载因子0.75
23         this(11, 0.75f);
24     }
25
26     public Hashtable(Map<? extends K, ? extends V> t) {
27         // 初始化容量为传入集合元素数量的2倍(至少为11),加载因子使用默认值0.75
28         this(Math.max(2*t.size(), 11), 0.75f);
29         putAll(t);
30     }
主要方法解析
- 扩容方法
这里与HashMap扩容时候有点区别,链表数据迁移时候,Hashtable是在链表头部插入(和之前链表反过来),HashMap是在尾部插入。
 1     protected void rehash() {
 2         int oldCapacity = table.length; // 原容量值
 3         Entry<?,?>[] oldMap = table;    // 原数组
 4
 5         // overflow-conscious code
 6         int newCapacity = (oldCapacity << 1) + 1;   // 预计扩容的容量为原容量的2倍+1
 7         if (newCapacity - MAX_ARRAY_SIZE > 0) {
 8             if (oldCapacity == MAX_ARRAY_SIZE)  // 预计扩容容量如果大于容量最大值,并且原容量为容量最大值,则不进行扩容处理
 9                 // Keep running with MAX_ARRAY_SIZE buckets
10                 return;
11             newCapacity = MAX_ARRAY_SIZE;   // 预计扩容容量如果大于容量最大值,则将新容量设置为容量最大值
12         }
13         Entry<?,?>[] newMap = new Entry<?,?>[newCapacity];  // 构建一个新数组
14
15         modCount++; // 修改次数+1
16         // 计算阈值。新容量值*加载因子,与容量最大值+1,两个比较取最小值
17         threshold = (int)Math.min(newCapacity * loadFactor, MAX_ARRAY_SIZE + 1);
18         table = newMap;
19
20         for (int i = oldCapacity ; i-- > 0 ;) {
21             // 遍历原数组,从后往前
22             for (Entry<K,V> old = (Entry<K,V>)oldMap[i] ; old != null ; ) {
23                 // 遍历该索引位链表,这里与jdk8中hashmap有点区别,这里是在链表头部插入(和之前链表会反过来),hashmap是在尾部插入
24                 Entry<K,V> e = old;
25                 old = old.next;
26
27                 int index = (e.hash & 0x7FFFFFFF) % newCapacity;
28                 e.next = (Entry<K,V>)newMap[index];
29                 newMap[index] = e;
30             }
31         }
32     }
- 添加元素
添加元素时,Hashtable与HashMap有3点区别:
- Hashtable的key-value都不允许为null。
- Hashtable是在链表头部插入(和之前链表反过来),HashMap是在尾部插入。
- Hashtable是先判断是否需要扩容,再插入元素;jdk8HashMap是先插入元素再判断是否需要扩容。
 1     public synchronized V put(K key, V value) {
 2         // Make sure the value is not null
 3         if (value == null) {
 4             // value为空,会抛出空指针异常
 5             throw new NullPointerException();
 6         }
 7
 8         // Makes sure the key is not already in the hashtable.
 9         Entry<?,?> tab[] = table;
10         int hash = key.hashCode();
11         int index = (hash & 0x7FFFFFFF) % tab.length;
12         @SuppressWarnings("unchecked")
13         Entry<K,V> entry = (Entry<K,V>)tab[index];
14         for(; entry != null ; entry = entry.next) {
15             if ((entry.hash == hash) && entry.key.equals(key)) {
16                 // 该key已经存在,直接替换原值
17                 V old = entry.value;
18                 entry.value = value;
19                 return old;
20             }
21         }
22         // 添加元素
23         addEntry(hash, key, value, index);
24         return null;
25     }
26     private void addEntry(int hash, K key, V value, int index) {
27         modCount++;
28
29         Entry<?,?> tab[] = table;
30         if (count >= threshold) {   // 判断是否元素数量是否达到阈值,如果达到先进行扩容处理
31             // Rehash the table if the threshold is exceeded
32             rehash();
33
34             tab = table;
35             hash = key.hashCode();
36             index = (hash & 0x7FFFFFFF) % tab.length;
37         }
38
39         // Creates the new entry.
40         @SuppressWarnings("unchecked")
41         Entry<K,V> e = (Entry<K,V>) tab[index];
42         // 插入元素是在链表头部插入
43         tab[index] = new Entry<>(hash, key, value, e);
44         count++;
45     }
- 删除元素
 1     public synchronized V remove(Object key) {
 2         Entry<?,?> tab[] = table;
 3         int hash = key.hashCode();
 4         int index = (hash & 0x7FFFFFFF) % tab.length;
 5         @SuppressWarnings("unchecked")
 6         Entry<K,V> e = (Entry<K,V>)tab[index];
 7         for(Entry<K,V> prev = null ; e != null ; prev = e, e = e.next) {
 8             if ((e.hash == hash) && e.key.equals(key)) {
 9                 modCount++;
10                 if (prev != null) {
11                     prev.next = e.next;
12                 } else {
13                     tab[index] = e.next;
14                 }
15                 count--;
16                 V oldValue = e.value;
17                 e.value = null;
18                 return oldValue;
19             }
20         }
21         return null;
22     }
23     public synchronized boolean remove(Object key, Object value) {
24         Objects.requireNonNull(value);
25
26         Entry<?,?> tab[] = table;
27         int hash = key.hashCode();
28         int index = (hash & 0x7FFFFFFF) % tab.length;
29         @SuppressWarnings("unchecked")
30         Entry<K,V> e = (Entry<K,V>)tab[index];
31         for (Entry<K,V> prev = null; e != null; prev = e, e = e.next) {
32             if ((e.hash == hash) && e.key.equals(key) && e.value.equals(value)) {
33                 modCount++;
34                 if (prev != null) {
35                     prev.next = e.next;
36                 } else {
37                     tab[index] = e.next;
38                 }
39                 count--;
40                 e.value = null;
41                 return true;
42             }
43         }
44         return false;
45     }
- 序列化/反序列化方法
1 private void writeObject(java.io.ObjectOutputStream s)
2 throws IOException {
3 Entry<Object, Object> entryStack = null;
4
5 synchronized (this) {
6 // Write out the threshold and loadFactor
7 s.defaultWriteObject();
8
9 // Write out the length and count of elements
10 s.writeInt(table.length);
11 s.writeInt(count);
12
13 // Stack copies of the entries in the table
14 for (int index = 0; index < table.length; index++) {
15 Entry<?,?> entry = table[index];
16
17 while (entry != null) {
18 entryStack =
19 new Entry<>(0, entry.key, entry.value, entryStack);
20 entry = entry.next;
21 }
22 }
23 }
24
25 // Write out the key/value objects from the stacked entries
26 while (entryStack != null) {
27 s.writeObject(entryStack.key);
28 s.writeObject(entryStack.value);
29 entryStack = entryStack.next;
30 }
31 }
32
33 private void readObject(java.io.ObjectInputStream s)
34 throws IOException, ClassNotFoundException
35 {
36 // Read in the threshold and loadFactor
37 s.defaultReadObject();
38
39 // Validate loadFactor (ignore threshold - it will be re-computed)
40 if (loadFactor <= 0 || Float.isNaN(loadFactor))
41 throw new StreamCorruptedException("Illegal Load: " + loadFactor);
42
43 // Read the original length of the array and number of elements
44 int origlength = s.readInt();
45 int elements = s.readInt();
46
47 // Validate # of elements
48 if (elements < 0)
49 throw new StreamCorruptedException("Illegal # of Elements: " + elements);
50
51 // Clamp original length to be more than elements / loadFactor
52 // (this is the invariant enforced with auto-growth)
53 origlength = Math.max(origlength, (int)(elements / loadFactor) + 1);
54
55 // Compute new length with a bit of room 5% + 3 to grow but
56 // no larger than the clamped original length. Make the length
57 // odd if it's large enough, this helps distribute the entries.
58 // Guard against the length ending up zero, that's not valid.
59 int length = (int)((elements + elements / 20) / loadFactor) + 3;
60 if (length > elements && (length & 1) == 0)
61 length--;
62 length = Math.min(length, origlength);
63
64 if (length < 0) { // overflow
65 length = origlength;
66 }
67
68 // Check Map.Entry[].class since it's the nearest public type to
69 // what we're actually creating.
70 SharedSecrets.getJavaOISAccess().checkArray(s, Map.Entry[].class, length);
71 table = new Entry<?,?>[length];
72 threshold = (int)Math.min(length * loadFactor, MAX_ARRAY_SIZE + 1);
73 count = 0;
74
75 // Read the number of elements and then all the key/value objects
76 for (; elements > 0; elements--) {
77 @SuppressWarnings("unchecked")
78 K key = (K)s.readObject();
79 @SuppressWarnings("unchecked")
80 V value = (V)s.readObject();
81 // sync is eliminated for performance
82 reconstitutionPut(table, key, value);
83 }
84 }
Dictionary
Java集合详解(五):Hashtable原理解析的更多相关文章
- Java集合详解4:一文读懂HashMap和HashTable的区别以及常见面试题
		<Java集合详解系列>是我在完成夯实Java基础篇的系列博客后准备开始写的新系列. 这些文章将整理到我在GitHub上的<Java面试指南>仓库,更多精彩内容请到我的仓库里查 ... 
- Java集合详解1:一文读懂ArrayList,Vector与Stack使用方法和实现原理
		本文非常详尽地介绍了Java中的三个集合类 ArrayList,Vector与Stack <Java集合详解系列>是我在完成夯实Java基础篇的系列博客后准备开始写的新系列. 这些文章将整 ... 
- Java集合详解6:TreeMap和红黑树
		Java集合详解6:TreeMap和红黑树 初识TreeMap 之前的文章讲解了两种Map,分别是HashMap与LinkedHashMap,它们保证了以O(1)的时间复杂度进行增.删.改.查,从存储 ... 
- Java集合详解6:这次,从头到尾带你解读Java中的红黑树
		<Java集合详解系列>是我在完成夯实Java基础篇的系列博客后准备开始写的新系列. 这些文章将整理到我在GitHub上的<Java面试指南>仓库,更多精彩内容请到我的仓库里查 ... 
- Java集合详解2:一文读懂Queue和LinkedList
		<Java集合详解系列>是我在完成夯实Java基础篇的系列博客后准备开始写的新系列. 这些文章将整理到我在GitHub上的<Java面试指南>仓库,更多精彩内容请到我的仓库里查 ... 
- Java集合详解8:Java的集合类细节精讲
		Java集合详解8:Java集合类细节精讲 今天我们来探索一下Java集合类中的一些技术细节.主要是对一些比较容易被遗漏和误解的知识点做一些讲解和补充.可能不全面,还请谅解. 本文参考:http:// ... 
- Java集合详解3:Iterator,fail-fast机制与比较器
		Java集合详解3:Iterator,fail-fast机制与比较器 今天我们来探索一下LIterator,fail-fast机制与比较器的源码. 具体代码在我的GitHub中可以找到 https:/ ... 
- Java集合详解8:Java集合类细节精讲,细节决定成败
		<Java集合详解系列>是我在完成夯实Java基础篇的系列博客后准备开始写的新系列. 这些文章将整理到我在GitHub上的<Java面试指南>仓库,更多精彩内容请到我的仓库里查 ... 
- Java集合详解7:一文搞清楚HashSet,TreeSet与LinkedHashSet的异同
		<Java集合详解系列>是我在完成夯实Java基础篇的系列博客后准备开始写的新系列. 这些文章将整理到我在GitHub上的<Java面试指南>仓库,更多精彩内容请到我的仓库里查 ... 
- Java集合详解3:一文读懂Iterator,fail-fast机制与比较器
		<Java集合详解系列>是我在完成夯实Java基础篇的系列博客后准备开始写的新系列. 这些文章将整理到我在GitHub上的<Java面试指南>仓库,更多精彩内容请到我的仓库里查 ... 
随机推荐
- PAT (Advanced Level) Practice 1019 General Palindromic Number  (20 分) 凌宸1642
			PAT (Advanced Level) Practice 1019 General Palindromic Number (20 分) 凌宸1642 题目描述: A number that will ... 
- 更改当前目录--cd
			pwd 显示当前所在的目录路径 cd ../ 回到上一层目录 cd ../../ 回到上上层目录 cd / 回到根目录 cd ~ 回到当前用户的根目录 c ... 
- C语言-字符串函数的实现(五)之strstr
			C语言中的字符串函数有如下这些 获取字符串长度 strlen 长度不受限制的字符串函数 strcpy strcat strcmp 长度受限制的字符串函数 strncpy strncat strncmp ... 
- Tree Recovery UVA - 536
			Little Valentine liked playing with binary trees very much. Her favorite game was constructing rando ... 
- Compound Words UVA - 10391
			You are to find all the two-word compound words in a dictionary. A two-word compound word is a wor ... 
- Day08_40_集合_List
			List集合 List接口是继承Collection接口,所以Collection集合中有的方法,List集合也会继承过来,可以直接使用. All Superinterfaces: Collectio ... 
- golang面向对象分析
			说道面向对象(OOP)编程, 就不得不提到下面几个概念: 抽象 封装 继承 多态 其实有个问题Is Go An Object Oriented Language?, 随便谷歌了一下, 你就发现讨论这个 ... 
- CPF 入门教程 - 设计器和模板库的使用(五)
			CPF netcore跨平台UI框架 系列教程 CPF 入门教程(一) CPF 入门教程 - 数据绑定和命令绑定(二) CPF 入门教程 - 样式和动画(三) CPF 入门教程 - 绘图(四) CPF ... 
- MVC之实现基于token的认证
			安装Nuget包 项目中添加包:dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer 添加认证配置 Startup类中添加如 ... 
- 转载:微信小程序view布局
			https://www.cnblogs.com/sun8134/p/6395947.html 
