一、结构图
Hashtable采用桶位+链表结构实现,如下图所示:
二、属性
2.1 table
底层是一个存储Entry的数组
private transient Entry<?,?>[] table;
2.2 Entry
一个单向链表结构
private static class Entry<K,V> implements Map.Entry<K,V> {
final int hash;
final K key;
V value;
Entry<K,V> next;
protected Entry(int hash, K key, V value, Entry<K,V> next) {
this.hash = hash;
this.key = key;
this.value = value;
this.next = next;
}
@SuppressWarnings("unchecked")
protected Object clone() {
return new Entry<>(hash, key, value,
(next==null ? null : (Entry<K,V>) next.clone()));
}
// Map.Entry Ops
public K getKey() {
return key;
}
public V getValue() {
return value;
}
public V setValue(V value) {
if (value == null)
throw new NullPointerException();
V oldValue = this.value;
this.value = value;
return oldValue;
}
public boolean equals(Object o) {
if (!(o instanceof Map.Entry))
return false;
Map.Entry<?,?> e = (Map.Entry<?,?>)o;
return (key==null ? e.getKey()==null : key.equals(e.getKey())) &&
(value==null ? e.getValue()==null : value.equals(e.getValue()));
}
public int hashCode() {
return hash ^ Objects.hashCode(value);
}
public String toString() {
return key.toString()+"="+value.toString();
}
}
2.3 相关参数
//记录了存储的元素数量
private transient int count;
//元素数量超过这个值后,会执行数组扩容
private int threshold;
//负载因子
private float loadFactor;
三、方法
3.1 构造方法
默认构造方法,构造一个大小为11,负载因子为0.75的HashTable
public Hashtable() {
this(11, 0.75f);
}
3.2 put
注意Key和Value都不能为空
//hashtable之所以是线程安全的,就是因为在put和get方法上使用了synchronized关键字进行修饰
public synchronized V put(K key, V value) {
//限制Value非空
if (value == null) {
throw new NullPointerException();
}
// Makes sure the key is not already in the hashtable.
Entry<?,?> tab[] = table;
//因为直接使用key.hashcode(),而没有像hashmap一样判断key是否是null,所以key为null时,调用key.hashcode()会出错,所以key也不能为空
int hash = key.hashCode();
//寻址的方式是取余
int index = (hash & 0x7FFFFFFF) % tab.length;
@SuppressWarnings("unchecked")
Entry<K,V> entry = (Entry<K,V>)tab[index];
for(; entry != null ; entry = entry.next) {
if ((entry.hash == hash) && entry.key.equals(key)) {
V old = entry.value;
entry.value = value;
return old;
}
}
//如果table[index]所连接的链表上不存在相同的key,则通过addEntry() 方法将新结点加载到链表的开头
addEntry(hash, key, value, index);
return null;
}
3.2.1 addEntry
private void addEntry(int hash, K key, V value, int index) {
modCount++;
Entry<?,?> tab[] = table;
//如果加入新结点后,hashtable中元素的个数超过了阈值threshold,则利用rehash()对数组进行扩容
if (count >= threshold) {
// Rehash the table if the threshold is exceeded
rehash();
tab = table;
hash = key.hashCode();
index = (hash & 0x7FFFFFFF) % tab.length;
}
//将新结点放在原结点前,相当于把新结点放在table[index]位置,即整个链表的首部
@SuppressWarnings("unchecked")
Entry<K,V> e = (Entry<K,V>) tab[index];
tab[index] = new Entry<>(hash, key, value, e);
count++;
}
3.2.1.1 rehash
增加数组容量,并重新调整整个hashtable。
@SuppressWarnings("unchecked")
protected void rehash() {
int oldCapacity = table.length;
Entry<?,?>[] oldMap = table;
// overflow-conscious code
//每次扩容,容量都变为原来的两倍
int newCapacity = (oldCapacity << 1) + 1;
if (newCapacity - MAX_ARRAY_SIZE > 0) {
if (oldCapacity == MAX_ARRAY_SIZE)
// Keep running with MAX_ARRAY_SIZE buckets
return;
newCapacity = MAX_ARRAY_SIZE;
}
Entry<?,?>[] newMap = new Entry<?,?>[newCapacity];
modCount++;
threshold = (int)Math.min(newCapacity * loadFactor, MAX_ARRAY_SIZE + 1);
table = newMap;
for (int i = oldCapacity ; i-- > 0 ;) {
for (Entry<K,V> old = (Entry<K,V>)oldMap[i] ; old != null ; ) {
Entry<K,V> e = old;
old = old.next;
int index = (e.hash & 0x7FFFFFFF) % newCapacity;
e.next = (Entry<K,V>)newMap[index];
newMap[index] = e;
}
}
}
3.3 get
如果存在键值对,那么返回key对应的值,否则返回null,返回的比较结果是通过equals返回的。
@SuppressWarnings("unchecked")
//hashtable线程安全的愿意,synchronized关键字
public synchronized V get(Object key) {
Entry<?,?> tab[] = table;
int hash = key.hashCode();
//利用哈希值进行寻址
int index = (hash & 0x7FFFFFFF) % tab.length;
//遍历table[index]链表,找到key值相同的结点的value并返回,注意这里同样使用了key的equals方法,所以key被应用于hashtable时,不仅要重写hashcode()方法,还要重写equals方法
for (Entry<?,?> e = tab[index] ; e != null ; e = e.next) {
if ((e.hash == hash) && e.key.equals(key)) {
return (V)e.value;
}
}
return null;
}
四、Hashtable和HashMap的区别总结
- hashmap中key和value均可以为null,但是hashtable中key和value均不能为null。
- hashmap采用的是数组(桶位)+链表+红黑树结构实现,而hashtable中采用的是数组(桶位)+链表实现。
- hashmap中出现hash冲突时,如果链表节点数小于8时是将新元素加入到链表的末尾,而hashtable中出现hash冲突时采用的是将新元素加入到链表的开头。
- hashmap中数组容量的大小要求是2的n次方,如果初始化时不符合要求会进行调整,而hashtable中数组容量的大小可以为任意正整数。
- hashmap中的寻址方法采用的是位运算按位与,而hashtable中寻址方式采用的是求余数。
- hashmap不是线程安全的,而hashtable是线程安全的,hashtable中的get和put方法均采用了synchronized关键字进行了方法同步。
- hashmap中默认容量的大小是16,而hashtable中默认数组容量是11。