HashMap和Hashtable的區(qū)別
1)兩者最主要的區(qū)別在于Hashtable是線程安全改艇,而HashMap則非線程安全
Hashtable的實(shí)現(xiàn)方法里面都添加了synchronized關(guān)鍵字來(lái)確保線程同步目木,因此相對(duì)而言HashMap性能會(huì)高一些组民,我們平時(shí)使用時(shí)若無(wú)特殊需求建議使用HashMap趾疚,在多線程環(huán)境下若使用HashMap需要使用Collections.synchronizedMap()方法來(lái)獲取一個(gè)線程安全的集合(Collections.synchronizedMap()實(shí)現(xiàn)原理是Collections定義了一個(gè)SynchronizedMap的內(nèi)部類,這個(gè)類實(shí)現(xiàn)了Map接口痛侍,在調(diào)用方法時(shí)使用synchronized來(lái)保證線程同步,當(dāng)然了實(shí)際上操作的還是我們傳入的HashMap實(shí)例钥弯,簡(jiǎn)單的說(shuō)就是Collections.synchronizedMap()方法幫我們?cè)诓僮鱄ashMap時(shí)自動(dòng)添加了synchronized來(lái)實(shí)現(xiàn)線程同步,類似的其它Collections.synchronizedXX方法也是類似原理)
2)HashMap可以使用null作為key垂寥,而Hashtable則不允許null作為key
雖說(shuō)HashMap支持null值作為key颠黎,不過建議還是盡量避免這樣使用另锋,因?yàn)橐坏┎恍⌒氖褂昧耍粢虼艘l(fā)一些問題狭归,排查起來(lái)很是費(fèi)事
HashMap以null作為key時(shí)夭坪,總是存儲(chǔ)在table數(shù)組的第一個(gè)節(jié)點(diǎn)上
3)HashMap是對(duì)Map接口的實(shí)現(xiàn),Hashtable實(shí)現(xiàn)了Map接口和Dictionary抽象類
4)HashMap的初始容量為16过椎,Hashtable初始容量為11室梅,兩者的填充因子默認(rèn)都是0.75
HashMap擴(kuò)容時(shí)是當(dāng)前容量翻倍即:capacity2,Hashtable擴(kuò)容時(shí)是容量翻倍+1即:capacity2+1
5)兩者計(jì)算hash的方法不同
Hashtable計(jì)算hash是直接使用key的hashcode對(duì)table數(shù)組的長(zhǎng)度直接進(jìn)行取模
int hash = key.hashCode();
int index = (hash & 0x7FFFFFFF) % tab.length;
HashMap計(jì)算hash對(duì)key的hashcode進(jìn)行了二次hash疚宇,以獲得更好的散列值亡鼠,然后對(duì)table數(shù)組長(zhǎng)度取摸
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的底層實(shí)現(xiàn)都是數(shù)組+鏈表結(jié)構(gòu)實(shí)現(xiàn)
HashSet和HashMap、Hashtable的區(qū)別
除開HashMap和Hashtable外敷待,還有一個(gè)hash集合HashSet间涵,有所區(qū)別的是HashSet不是key value結(jié)構(gòu),僅僅是存儲(chǔ)不重復(fù)的元素榜揖,相當(dāng)于簡(jiǎn)化版的HashMap勾哩,只是包含HashMap中的key而已。
通過查看源碼也證實(shí)了這一點(diǎn)举哟,HashSet內(nèi)部就是使用HashMap實(shí)現(xiàn)思劳,只不過HashSet里面的HashMap所有的value都是同一個(gè)Object而已,因此HashSet也是非線程安全的妨猩,至于HashSet和Hashtable的區(qū)別敢艰,HashSet就是個(gè)簡(jiǎn)化的HashMap的,所以你懂的册赛。
下面是HashSet幾個(gè)主要方法的實(shí)現(xiàn)
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的實(shí)現(xiàn)原理
HashMap和Hashtable的底層實(shí)現(xiàn)都是數(shù)組+鏈表結(jié)構(gòu)實(shí)現(xiàn)的钠导,這點(diǎn)上完全一致。
添加森瘪、刪除牡属、獲取元素時(shí)都是先計(jì)算hash,根據(jù)hash和table.length計(jì)算index也就是table數(shù)組的下標(biāo)扼睬,然后進(jìn)行相應(yīng)操作逮栅,下面以HashMap為例說(shuō)明下它的簡(jiǎn)單實(shí)現(xiàn)
/**
* HashMap的默認(rèn)初始容量 必須為2的n次冪
*/
static final int DEFAULT_INITIAL_CAPACITY = 16;
/**
* HashMap的最大容量,可以認(rèn)為是int的最大值
*/
static final int MAXIMUM_CAPACITY = 1 << 30;
/**
* 默認(rèn)的加載因子
*/
static final float DEFAULT_LOAD_FACTOR = 0.75f;
/**
* HashMap用來(lái)存儲(chǔ)數(shù)據(jù)的數(shù)組
*/
transient Entry[] table;
HashMap的創(chuàng)建
HashMap默認(rèn)初始化時(shí)會(huì)創(chuàng)建一個(gè)默認(rèn)容量為16的Entry數(shù)組窗宇,默認(rèn)加載因子為0.75措伐,同時(shí)設(shè)置臨界值為16*0.75
/**
Constructs an empty <tt>HashMap</tt> 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會(huì)對(duì)null值key進(jìn)行特殊處理,總是放到table[0]位置
put過程是先計(jì)算hash然后通過hash與table.length取摸計(jì)算index值军俊,然后將key放到table[index]位置侥加,當(dāng)table[index]已存在其它元素時(shí),會(huì)在table[index]位置形成一個(gè)鏈表粪躬,將新添加的元素放在table[index]担败,原來(lái)的元素通過Entry的next進(jìn)行鏈接昔穴,這樣以鏈表形式解決hash沖突問題,當(dāng)元素?cái)?shù)量達(dá)到臨界值(capactiyfactor)時(shí)提前,則進(jìn)行擴(kuò)容吗货,是table數(shù)組長(zhǎng)度變?yōu)閠able.length2
public V put(K key, V value) {
if (key == null)
return putForNullKey(value); //處理null值
int hash = hash(key.hashCode());//計(jì)算hash
int i = indexFor(hash, table.length);//計(jì)算在數(shù)組中的存儲(chǔ)位置
//遍歷table[i]位置的鏈表,查找相同的key狈网,若找到則使用新的value替換掉原來(lái)的oldValue并返回oldValue
for (Entry 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]位置的第一個(gè)元素拓哺,原來(lái)的元素后移
modCount++;
addEntry(hash, key, value, i);
return null;
}
void addEntry(int hash, K key, V value, int bucketIndex) {
//添加key到table[bucketIndex]位置勇垛,新的元素總是在table[bucketIndex]的第一個(gè)元素,原來(lái)的元素后移
Entry<K,V> e = table[bucketIndex];
table[bucketIndex] = new Entry(hash, key, value, e);
//判斷元素個(gè)數(shù)是否達(dá)到了臨界值拓售,若已達(dá)到臨界值則擴(kuò)容,table長(zhǎng)度翻倍
if (size++ >= threshold)
resize(2 * table.length);
}
get方法
同樣當(dāng)key為null時(shí)會(huì)進(jìn)行特殊處理镶奉,在table[0]的鏈表上查找key為null的元素
get的過程是先計(jì)算hash然后通過hash與table.length取摸計(jì)算index值础淤,然后遍歷table[index]上的鏈表,直到找到key哨苛,然后返回
public V get(Object key) {
if (key == null)
return getForNullKey();//處理null值
int hash = hash(key.hashCode());//計(jì)算hash
//在table[index]遍歷查找key鸽凶,若找到則返回value,找不到返回null
for (Entry 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類似建峭,計(jì)算hash玻侥,計(jì)算index,然后遍歷查找亿蒸,將找到的元素從table[index]鏈表移除
public V remove(Object key) {
Entry 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 prev = table[i];
Entry e = prev;
while (e != null) {
Entry 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中并沒有公開凑兰,這個(gè)方法實(shí)現(xiàn)了非常重要的hashmap擴(kuò)容,具體過程為:先創(chuàng)建一個(gè)容量為table.length2的新table边锁,修改臨界值姑食,然后把table里面元素計(jì)算hash值并使用hash與table.length2重新計(jì)算index放入到新的table里面。
這里需要注意下是用每個(gè)元素的hash全部重新計(jì)算index茅坛,而不是簡(jiǎn)單的把原table對(duì)應(yīng)index位置元素簡(jiǎn)單的移動(dòng)到新table對(duì)應(yīng)位置
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 e = src[j];
if (e != null) {
src[j] = null;
do {
Entry next = e.next;
//重新對(duì)每個(gè)元素計(jì)算index
int i = indexFor(e.hash, newCapacity);
e.next = newTable[i];
newTable[i] = e;
e = next;
} while (e != null);
}
}
}
clear()方法
clear方法非常簡(jiǎn)單音半,就是遍歷table然后把每個(gè)位置置為null,同時(shí)修改元素個(gè)數(shù)為0贡蓖,需要注意的是clear方法只會(huì)清楚里面的元素曹鸠,并不會(huì)重置capactiy。
public void clear() {
modCount++;
Entry[] tab = table;
for (int i = 0; i < tab.length; i++)
tab[i] = null;
size = 0;
}
containsKey和containsValue
containsKey方法是先計(jì)算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 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方法本質(zhì)上和普通數(shù)組和list的contains方法沒什么區(qū)別晾蜘,你別指望它會(huì)像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)就相當(dāng)于h%length叛薯,用于計(jì)算index也就是在table數(shù)組中的下標(biāo)
hash方法是對(duì)hashcode進(jìn)行二次散列浑吟,以獲得更好的散列值
為了更好理解這里我們可以把這兩個(gè)方法簡(jiǎn)化為int index= key.hashCode()/table.length,以put中的方法為例可以這樣替換
int hash = hash(key.hashCode());//計(jì)算hash
int i = indexFor(hash, table.length);//計(jì)算在數(shù)組中的存儲(chǔ)位置
//上面這兩行可以這樣簡(jiǎn)化
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);
}