hashtable的實現和hashmap差不多,兩者之間只存在幾點不同。
hashtable採用「拉鍊法」實現雜湊表。
table:為乙個entry陣列型別,代表了拉鍊的節點。每乙個entry代表乙個key-value。
private transient entry<?,?> table;
count:entry鍵值對的數量
private transient int count;
threshold:hashtable的閾值,用於判斷是否需要調整hashtable的容量。threshold的值=容量*載入因子
private int threshold;
modcount:用來實現「fail-fast」機制的(也就是快速失敗)。所謂快速失敗就是在併發集合中,其進行迭代操作時,若有其他執行緒對其進行結構性的修改,這時迭代器會立馬感知到,並且立即丟擲concurrentmodificationexception異常,而不是等到迭代完成之後才告訴你(你已經出錯了)。
private transient int modcount = 0;
public hashtable(int initialcapacity, float loadfactor)
public synchronized v put(k key, v value)
// makes sure the key is not already in the hashtable.
entry<?,?> tab = table;
//獲取hashcode
int hash = key.hashcode();
//獲取雜湊桶索引
int index = (hash & 0x7fffffff) % tab.length;
@suppresswarnings("unchecked")
entryentry = (entry)tab[index];
for(; entry != null ; entry = entry.next)
}//如果物件之前不存在,則新增
addentry(hash, key, value, index);
return null;
}
private void addentry(int hash, k key, v value, int index)
// creates the new entry.
@suppresswarnings("unchecked")
entrye = (entry) tab[index];
//增加新元素
tab[index] = new entry<>(hash, key, value, e);
count++;
}
put方法的處理流程
計算key的hash值
根據hash值獲取table中的索引
迭代該處的entry鍊錶,檢視是否有對應的key,有則替換value,否則新建插入。
hashtable中的entry實現了map中的entry
private static class entryimplements map.entry
@suppresswarnings("unchecked")
protected object clone()
// map.entry ops
public k getkey()
public v getvalue()
public v setvalue(v value)
public boolean equals(object o)
public int hashcode()
public string tostring()
}
get方法處理過程就是計算key的hash,得到table處的index,之後對entry進行迭代,找到相對於key的value
public synchronized v get(object key)
}return null;
}
1.hashtable基於dictionary類,hashmap基於abstractmap。dictionary是什麼?它是任何可將鍵對映到相應值的類的抽象父類,而abstractmap是基於map介面的骨幹實現,它以最大限度地減少實現此介面所需的工作。
2.hashmap可以允許存在乙個為null的key和任意個為null的value,但是hashtable中的key和value都不允許為null。
3.hashtable的方法是同步的,而hashmap的方法不是。所以有人一般都建議如果是涉及到多執行緒同步時採用hashtable,沒有涉及就採用hashmap。
死磕mysql 死磕mysql
資料庫建立語句 create database new 建立乙個名為new 的資料庫 drop database new 刪除名為new的資料庫 資料庫名為小寫,當初教我的那個人對我說在某個系統中大寫會出現異常情況,為了方便移植,統一為小寫 show creata database new 檢視建立...
死磕動態規劃
乙個模型三個特徵 理論講解什麼樣的問題適合用動態規劃來解決呢?換句話說,動態規劃能解決的問題有什麼規律可循呢?實際上,動態規劃作為乙個非常成熟的演算法思想,很多人對此已經做了非常全面的總結。我把這部分理論總結為 乙個模型三個特徵 首先,我們來看,什麼是 乙個模型 它指的是動態規劃適合解決的問題的模型...
死磕有效括號
目錄 1 leetcode20.有效的括號 2 leetcode22.括號生成 3 leetcode32.最長有效括號 3.1 滑動視窗暴力破解 3.2 借助棧 3.3 動態規劃 給定乙個只包括 的字串,判斷字串是否有效。有效字串需滿足 左括號必須用相同型別的右括號閉合。左括號必須以正確的順序閉合。...