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;
分享一個寫的想好的博客給大家: