1. 程式人生 > 實用技巧 >HashMap和Hashtable的區別

HashMap和Hashtable的區別

兩者最主要的區別在於Hashtable是執行緒安全,而HashMap則非執行緒安全
Hashtable的實現方法裡面都添加了synchronized關鍵字來確保執行緒同步,因此相對而言HashMap效能會高一些,我們平時使用時若無特殊需求建議使用HashMap,在多執行緒環境下若使用HashMap需要使用Collections.synchronizedMap()方法來獲取一個執行緒安全的集合(Collections.synchronizedMap()實現原理是Collections定義了一個SynchronizedMap的內部類,這個類實現了Map介面,在呼叫方法時使用synchronized來保證執行緒同步,當然了實際上操作的還是我們傳入的HashMap例項,簡單的說就是Collections.synchronizedMap()方法幫我們在操作HashMap時自動添加了synchronized來實現執行緒同步,類似的其它Collections.synchronizedXX方法也是類似原理)
HashMap可以使用null作為key,而Hashtable則不允許null作為key
雖說HashMap支援null值作為key,不過建議還是儘量避免這樣使用,因為一旦不小心使用了,若因此引發一些問題,排查起來很是費事
HashMap以null作為key時,總是儲存在table陣列的第一個節點上
HashMap是對Map介面的實現,HashTable實現了Map介面和Dictionary抽象類
HashMap的初始容量為16,Hashtable初始容量為11,兩者的填充因子預設都是0.75
HashMap擴容時是當前容量翻倍即:capacity2,Hashtable擴容時是容量翻倍+1即:capacity

2+1
兩者計算hash的方法不同
Hashtable計算hash是直接使用key的hashcode對table陣列的長度直接進行取模
int hash = key.hashCode();
int index = (hash & 0x7FFFFFFF) % tab.length;
HashMap計算hash對key的hashcode進行了二次hash,以獲得更好的雜湊值,然後對table陣列長度取摸

複製程式碼
static int hash(int h) {
// This function ensures that hashCodes that differ only by
// constant multiples at each bit position have a bounded
// number of collisions (approximately 8 at default load factor).
h ^= (h >>> 20) ^ (h >>> 12);
return h ^ (h >>> 7) ^ (h >>> 4);
}

static int indexFor(int h, int length) {
return h & (length-1);
}
複製程式碼

HashMap和Hashtable的底層實現都是陣列+連結串列結構實現
HashSet和HashMap、Hashtable的區別
除開HashMap和Hashtable外,還有一個hash集合HashSet,有所區別的是HashSet不是key value結構,僅僅是儲存不重複的元素,相當於簡化版的HashMap,只是包含HashMap中的key而已

通過檢視原始碼也證實了這一點,HashSet內部就是使用HashMap實現,只不過HashSet裡面的HashMap所有的value都是同一個Object而已,因此HashSet也是非執行緒安全的,至於HashSet和Hashtable的區別,HashSet就是個簡化的HashMap的,所以你懂的
下面是HashSet幾個主要方法的實現

複製程式碼
private transient HashMap<E,Object> map;
private static final Object PRESENT = new Object();

public HashSet() {
map = new HashMap<E,Object>();
}
public boolean contains(Object o) {
return map.containsKey(o);
}
public boolean add(E e) {
return map.put(e, PRESENT)null;
}
public boolean add(E e) {
return map.put(e, PRESENT)
null;
}
public boolean remove(Object o) {
return map.remove(o)==PRESENT;
}

public void clear() {
map.clear();
}
複製程式碼

HashMap和Hashtable的實現原理
HashMap和Hashtable的底層實現都是陣列+連結串列結構實現的,這點上完全一致

新增、刪除、獲取元素時都是先計算hash,根據hash和table.length計算index也就是table陣列的下標,然後進行相應操作,下面以HashMap為例說明下它的簡單實現

複製程式碼
/**
* HashMap的預設初始容量 必須為2的n次冪
*/
static final int DEFAULT_INITIAL_CAPACITY = 16;

/**
 * HashMap的最大容量,可以認為是int的最大值    
 */
static final int MAXIMUM_CAPACITY = 1 << 30;

/**
 * 預設的載入因子
 */
static final float DEFAULT_LOAD_FACTOR = 0.75f;

/**
 * HashMap用來儲存資料的陣列
 */
transient Entry[] table;

複製程式碼
HashMap的建立
HashMap預設初始化時會建立一個預設容量為16的Entry陣列,預設載入因子為0.75,同時設定臨界值為16*0.75
複製程式碼
/**
* Constructs an empty HashMap with the default initial capacity
* (16) and the default load factor (0.75).
*/
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR;
threshold = (int)(DEFAULT_INITIAL_CAPACITY * DEFAULT_LOAD_FACTOR);
table = new Entry[DEFAULT_INITIAL_CAPACITY];
init();
}
複製程式碼

put方法
HashMap會對null值key進行特殊處理,總是放到table[0]位置
put過程是先計算hash然後通過hash與table.length取摸計算index值,然後將key放到table[index]位置,當table[index]已存在其它元素時,會在table[index]位置形成一個連結串列,將新新增的元素放在table[index],原來的元素通過Entry的next進行連結,這樣以連結串列形式解決hash衝突問題,當元素數量達到臨界值(capactiyfactor)時,則進行擴容,是table陣列長度變為table.length2
複製程式碼
public V put(K key, V value) {
if (key == null)
return putForNullKey(value); //處理null值
int hash = hash(key.hashCode());//計算hash
int i = indexFor(hash, table.length);//計算在陣列中的儲存位置
//遍歷table[i]位置的連結串列,查詢相同的key,若找到則使用新的value替換掉原來的oldValue並返回oldValue
for (Entry<K,V> e = table[i]; e != null; e = e.next) {
Object k;
if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
V oldValue = e.value;
e.value = value;
e.recordAccess(this);
return oldValue;
}
}
//若沒有在table[i]位置找到相同的key,則新增key到table[i]位置,新的元素總是在table[i]位置的第一個元素,原來的元素後移
modCount++;
addEntry(hash, key, value, i);
return null;
}

void addEntry(int hash, K key, V value, int bucketIndex) {
//新增key到table[bucketIndex]位置,新的元素總是在table[bucketIndex]的第一個元素,原來的元素後移
Entry<K,V> e = table[bucketIndex];
    table[bucketIndex] = new Entry<K,V>(hash, key, value, e);
//判斷元素個數是否達到了臨界值,若已達到臨界值則擴容,table長度翻倍
    if (size++ >= threshold)
        resize(2 * table.length);
}

複製程式碼

get方法
同樣當key為null時會進行特殊處理,在table[0]的連結串列上查詢key為null的元素
get的過程是先計算hash然後通過hash與table.length取摸計算index值,然後遍歷table[index]上的連結串列,直到找到key,然後返回
複製程式碼
public V get(Object key) {
if (key == null)
return getForNullKey();//處理null值
int hash = hash(key.hashCode());//計算hash
//在table[index]遍歷查詢key,若找到則返回value,找不到返回null
for (Entry<K,V> e = table[indexFor(hash, table.length)];
e != null;
e = e.next) {
Object k;
if (e.hash == hash && ((k = e.key) == key || key.equals(k)))
return e.value;
}
return null;
}
複製程式碼

remove方法
remove方法和put get類似,計算hash,計算index,然後遍歷查詢,將找到的元素從table[index]連結串列移除
複製程式碼
public V remove(Object key) {
Entry<K,V> e = removeEntryForKey(key);
return (e == null ? null : e.value);
}
final Entry<K,V> removeEntryForKey(Object key) {
int hash = (key == null) ? 0 : hash(key.hashCode());
int i = indexFor(hash, table.length);
Entry<K,V> prev = table[i];
Entry<K,V> e = prev;

    while (e != null) {
        Entry<K,V> next = e.next;
        Object k;
        if (e.hash == hash &&
            ((k = e.key) == key || (key != null && key.equals(k)))) {
            modCount++;
            size--;
            if (prev == e)
                table[i] = next;
            else
                prev.next = next;
            e.recordRemoval(this);
            return e;
        }
        prev = e;
        e = next;
    }

    return e;
}

複製程式碼

resize方法
resize方法在hashmap中並沒有公開,這個方法實現了非常重要的hashmap擴容,具體過程為:先建立一個容量為table.length2的新table,修改臨界值,然後把table裡面元素計算hash值並使用hash與table.length2重新計算index放入到新的table裡面
這裡需要注意下是用每個元素的hash全部重新計算index,而不是簡單的把原table對應index位置元素簡單的移動到新table對應位置
複製程式碼
void resize(int newCapacity) {
Entry[] oldTable = table;
int oldCapacity = oldTable.length;
if (oldCapacity == MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return;
}

    Entry[] newTable = new Entry[newCapacity];
    transfer(newTable);
    table = newTable;
    threshold = (int)(newCapacity * loadFactor);
}

void transfer(Entry[] newTable) {
    Entry[] src = table;
    int newCapacity = newTable.length;
    for (int j = 0; j < src.length; j++) {
        Entry<K,V> e = src[j];
        if (e != null) {
            src[j] = null;        
            do {
                Entry<K,V> next = e.next;
                //重新對每個元素計算index
                int i = indexFor(e.hash, newCapacity);
                e.next = newTable[i];
                newTable[i] = e;
                e = next;
            } while (e != null);
        }
    }
}

複製程式碼

clear()方法
clear方法非常簡單,就是遍歷table然後把每個位置置為null,同時修改元素個數為0
需要注意的是clear方法只會清楚裡面的元素,並不會重置capactiy
複製程式碼
public void clear() {
modCount++;
Entry[] tab = table;
for (int i = 0; i < tab.length; i++)
tab[i] = null;
size = 0;
}
複製程式碼

containsKey和containsValue
containsKey方法是先計算hash然後使用hash和table.length取摸得到index值,遍歷table[index]元素查詢是否包含key相同的值
複製程式碼
public boolean containsKey(Object key) {
return getEntry(key) != null;
}
final Entry<K,V> getEntry(Object key) {
int hash = (key == null) ? 0 : hash(key.hashCode());
for (Entry<K,V> e = table[indexFor(hash, table.length)];
e != null;
e = e.next) {
Object k;
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
}
return null;
}
複製程式碼
containsValue方法就比較粗暴了,就是直接遍歷所有元素直到找到value,由此可見HashMap的containsValue方法本質上和普通陣列和list的contains方法沒什麼區別,你別指望它會像containsKey那麼高效

複製程式碼
public boolean containsValue(Object value) {
if (value == null)
return containsNullValue();

Entry[] tab = table;
    for (int i = 0; i < tab.length ; i++)
        for (Entry e = tab[i] ; e != null ; e = e.next)
            if (value.equals(e.value))
                return true;
return false;
}

複製程式碼

hash和indexFor
indexFor中的h & (length-1)就相當於h%length,用於計算index也就是在table陣列中的下標
hash方法是對hashcode進行二次雜湊,以獲得更好的雜湊值
為了更好理解這裡我們可以把這兩個方法簡化為 int index= key.hashCode()/table.length,以put中的方法為例可以這樣替換
int hash = hash(key.hashCode());//計算hash
int i = indexFor(hash, table.length);//計算在陣列中的儲存位置
//上面這兩行可以這樣簡化
int i = key.key.hashCode()%table.length;

複製程式碼
static int hash(int h) {
// This function ensures that hashCodes that differ only by
// constant multiples at each bit position have a bounded
// number of collisions (approximately 8 at default load factor).
h ^= (h >>> 20) ^ (h >>> 12);
return h ^ (h >>> 7) ^ (h >>> 4);
}

static int indexFor(int h, int length) {
    return h & (length-1);
}

複製程式碼

HashMap的簡化實現MyHashMap
為了加深理解,我個人實現了一個簡化版本的HashMap,注意哦,僅僅是簡化版的功能並不完善,僅供參考

MyHashMap

注:此文章屬懶惰的肥兔原創,版權歸作者和部落格園共有,歡迎轉載,但未經作者同意必須保留此段宣告,且在文章頁面明顯位置給出原文連線

若您覺得這篇文章還不錯請點選下右下角的推薦,有了您的支援才能激發作者更大的寫作熱情,非常感謝。

如有問題,可以通過[email protected]聯絡我。

來自:https://www.cnblogs.com/lzrabbit/p/3721067.html