HashTable 1.8源码分析
首先回顾一下HashTable的特性:
线程安全,Key Value 都不能为空。 数据结构: 数组 + 链表,默认数组的长度是11 , 扩容时为原来的两倍+1,阈值是0.75。 父类是 Dictionary<K,V>.。使用的是Enumeration迭代。 public 方法都使用了synchronize关键字。多线程情况是安全了,就是会造成排队,影响性能。
几个比较重要的属性
private transient Entry<?,?>[] table; // 数组 默认值11
private transient int count; //计数 默认值0
private int threshold ; // 阈值 table.length * loadFactor
private float loadFactor; // 负载因子 默认值 0.75
private transient int modCount = 0;//用来帮助实现fail-fast机制
fail-fast 机制,即快速失败机制,是java集合(Collection)中的一种错误检测机制。当在迭代集合的过程中该集合在结构上发生改变的时候,就有可能会发生fail-fast,即抛出ConcurrentModificationException异常。fail-fast机制并不保证在不同步的修改下一定会抛出异常,它只是尽最大努力去抛出,所以这种机制一般仅用于检测bug。
HashTable 构造方法
一共四个构造方法
- Hashtable(int initialCapacity, float loadFactor)自定义数组的初始容量和负载因子
- public Hashtable(int initialCapacity) 自定义数组的初始容量
- public Hashtable()全部使用默认的参数
- public Hashtable(Map<? extends K, ? extends V> t) 带参构造
public Hashtable(int initialCapacity, float loadFactor) {
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
if (loadFactor <= 0 || Float.isNaN(loadFactor))
throw new IllegalArgumentException("Illegal Load: "+loadFactor);
if (initialCapacity==0)
initialCapacity = 1;
this.loadFactor = loadFactor;
table = new Entry<?,?>[initialCapacity];
threshold = (int)Math.min(initialCapacity * loadFactor, MAX_ARRAY_SIZE + 1);
}
public Hashtable(int initialCapacity) {
this(initialCapacity, 0.75f);
}
public Hashtable() {
this(11, 0.75f);
}
public Hashtable(Map<? extends K, ? extends V> t) {
this(Math.max(2*t.size(), 11), 0.75f);
putAll(t);
}
get() 源码解析
public synchronized V get(Object key) {
Entry<?,?> tab[] = table;
int hash = key.hashCode();
int index = (hash & 0x7FFFFFFF) % tab.length; // 计算下标这个和Hashmap一样的算法
for (Entry<?,?> e = tab[index] ; e != null ; e = e.next) { //循环比较
if ((e.hash == hash) && e.key.equals(key)) {
return (V)e.value;
}
}
return null;
}
containsValue()and contains()源码看看
嗯,没啥好说的!就是这两个方法其实用的都是contains()方法。
public boolean containsValue(Object value) {
return contains(value);
}
public synchronized boolean containsKey(Object key) {
Entry<?,?> tab[] = table;
int hash = key.hashCode();
int index = (hash & 0x7FFFFFFF) % tab.length;
for (Entry<?,?> e = tab[index] ; e != null ; e = e.next) {
if ((e.hash == hash) && e.key.equals(key)) {
return true;
}
}
return false;
}
containsKey源码
过!
public synchronized boolean containsKey(Object key) {
Entry<?,?> tab[] = table;
int hash = key.hashCode();
int index = (hash & 0x7FFFFFFF) % tab.length;
for (Entry<?,?> e = tab[index] ; e != null ; e = e.next) {
if ((e.hash == hash) && e.key.equals(key)) {
return true;
}
}
return false;
}
put 源码
value 不能为空! 会报错的。
为啥没判断key是不是空,因为要通过key.hashCode()的值去计算数组下标位置,key是空运行到这一步自己就报空指针异常的。
public synchronized V put(K key, V value) {
// Make sure the value is not null
if (value == null) {
throw new NullPointerException();
}
// Makes sure the key is not already in the hashtable.
Entry<?,?> tab[] = table;
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;
}
}
addEntry(hash, key, value, index);
return null;
}
addEntry 源码
它是私有的方法,所用没有用同步锁。
private void addEntry(int hash, K key, V value, int index) {
modCount++; // 添加了元素 要++ 计算总数
Entry<?,?> tab[] = table;
if (count >= threshold) { // 是否超过阈值
// Rehash the table if the threshold is exceeded
rehash(); // 扩容数组
//扩容后会重新只算位置
tab = table;
hash = key.hashCode();
index = (hash & 0x7FFFFFFF) % tab.length;
}
// Creates the new entry.
@SuppressWarnings("unchecked")
Entry<K,V> e = (Entry<K,V>) tab[index];
tab[index] = new Entry<>(hash, key, value, e);
count++;
}
rehash 源码
protected void rehash() {
int oldCapacity = table.length;
Entry<?,?>[] oldMap = table;
// overflow-conscious code
int newCapacity = (oldCapacity << 1) + 1; // 扩容到 原数组的2倍+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;
}
}
}
remove 源码
public synchronized V remove(Object key) {
Entry<?,?> tab[] = table;
int hash = key.hashCode();
int index = (hash & 0x7FFFFFFF) % tab.length;
@SuppressWarnings("unchecked")
Entry<K,V> e = (Entry<K,V>)tab[index];
for(Entry<K,V> prev = null ; e != null ; prev = e, e = e.next) {
if ((e.hash == hash) && e.key.equals(key)) {
modCount++;
if (prev != null) {
prev.next = e.next;
} else {
tab[index] = e.next;
}
count--;
V oldValue = e.value;
e.value = null;
return oldValue;
}
}
return null;
}
clear 源码
简单粗暴
public synchronized void clear() {
Entry<?,?> tab[] = table;
modCount++;
for (int index = tab.length; --index >= 0; )
tab[index] = null;
count = 0;
}
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;
}
HashMap HashTable 的区别
源码看过了,咋们比较比较吧!
- HashMap 的父类AbstractMap HashTable 的父类是 Dictionary
- HashMap 的默认容量是16 HashTable的默认容量是11
- HashMap 扩容是翻一倍 HashTable 扩容是翻一倍 +1
- HashMap 是线程不安全的 HashTable 是线程安全的 每一个public方法都加上了 同步锁 synchronize
- HashMap key value 可以为空,key只能是一个为空,value可以是多个。 HashTable key value 都不可一为空。
- HashMap 的数据结构是 数组 + 链表 + 红黑树 HashTable的数据结构是 数组 + 链表
- HashMap 中没有contains()方法, HashTable中有contains() 这个方法, 方法内部调动是containsValue(),这点可以忽略
- Hashtable、HashMap都使用了 Iterator。而由于历史原因,Hashtable还使用了Enumeration的方式 。
- HashMap 的hash值计算 (n - 1) & hash == (数组长度-1)& key.hashCode
HashTable 的hash值计算 (hash & 0x7FFFFFFF) % tab.length;
分享一个写的想好的博客给大家: