原文鏈接http://zhhll.icu/2020/11/12/java%E5%9F%BA%E7%A1%80/%E9%9B%86%E5%90%88/Map/
Map
Map是一個介面,下面介紹一下Map介面的一些常用的實作類
Hashtable
Hashtable是在java1.0中實作的最早的Map,繼承自Dictionary類,底層使用的哈希表,是執行緒安全的,因為該類中的方法都是用了synchronized修飾,但是也因此存在了效率問題
如果想要使用具有用執行緒安全能力的map可以使用Collections.synchronizedMap()方法或者使用ConcurrentHashMap
public class Hashtable<K,V>
extends Dictionary<K,V>
implements Map<K,V>, Cloneable, java.io.Serializable {
@SuppressWarnings("unchecked")
public synchronized V get(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 (V)e.value;
}
}
return null;
}
內部所使用的是一個Entry陣列進行存盤的,Entry實際上是一個鏈表,key和value都保存在Entry中
/**
* The hash table data.
*/
private transient Entry<?,?>[] table;
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 = https://www.cnblogs.com/life-time/archive/2021/01/27/value;
this.next = next;
}
@SuppressWarnings("unchecked")
protected Object clone() {
return new Entry<>(hash, key, value,
(next==null ? null : (Entry<K,V>) next.clone()));
}
// Map.Entry Ops
public K getKey() {
return key;
}
public V getValue() {
return value;
}
public V setValue(V value) {
if (value =https://www.cnblogs.com/life-time/archive/2021/01/27/= null)
throw new NullPointerException();
V oldValue = this.value;
this.value = value;
return oldValue;
}
public boolean equals(Object o) {
if (!(o instanceof Map.Entry))
return false;
Map.Entry<?,?> e = (Map.Entry<?,?>)o;
return (key==null ? e.getKey()==null : key.equals(e.getKey())) &&
(value==null ? e.getValue()==null : value.equals(e.getValue()));
}
public int hashCode() {
return hash ^ Objects.hashCode(value);
}
public String toString() {
return key.toString()+"="+value.toString();
}
}
HashTable的key和value都不允許為null,可以看到在put操作的時候,會校驗value值是否為null,而且會獲取key的hashCode,所以key和value都不可以為null
public synchronized V put(K key, V value) {
// Make sure the value is not null
if (value =https://www.cnblogs.com/life-time/archive/2021/01/27/= 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 = https://www.cnblogs.com/life-time/archive/2021/01/27/value;
return old;
}
}
addEntry(hash, key, value, index);
return null;
}
HashMap
當前用的最多的還是HashMap
HashMap是執行緒不安全的,底層也是哈希表,與HashTable不同的是,key和value可以為null
可以看到在put方法取key的hash值時對key進行了判斷,key為null的話,hash值為0
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
HashMap的底層使用Node陣列來存盤的
transient Node<K,V>[] table;
HashMap如果出現hash沖突的話,會在放到鏈表中,但是如果hash沖突過多的話,會導致鏈表太長,查詢時性能會下降,在鏈表長度超過一定值時,會進行結構改造,將鏈表轉換為樹狀結構,這里TREEIFY_THRESHOLD是8
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
if ((tab = table) == null || (n = tab.length) == 0) // table為null,進行初始化
n = (tab = resize()).length;
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
// 遍歷map
for (int binCount = 0; ; ++binCount) {
// 遍歷完依舊沒有該key,需要添加一個新的節點
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
// 鏈表轉為樹狀結構
treeifyBin(tab, hash);
break;
}
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
if (e != null) { // existing mapping for key
V oldValue = https://www.cnblogs.com/life-time/archive/2021/01/27/e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
TreeMap
TreeMap底層是紅黑樹,實作了SortedMap介面,順序由key控制(默認是按key進行,key必須實作Comparable介面或者在構造器傳入自定義的Comparator),通過Comparator或者Comparable決定,
public class TreeMap<K,V>
extends AbstractMap<K,V>
implements NavigableMap<K,V>, Cloneable, java.io.Serializable
public interface NavigableMap<K,V> extends SortedMap<K,V>
// key進行比較
final int compare(Object k1, Object k2) {
return comparator==null ? ((Comparable<? super K>)k1).compareTo((K)k2)
: comparator.compare((K)k1, (K)k2);
}
LinkedHashMap
LinkedHashMap屬于一個雙向鏈表,通過鍵值來維護,遍歷順序為插入順序,相當于一個有順序的HashMap
增加了兩個屬性來保證迭代順序,分別是雙向鏈表的頭結點header和標志位accessOrder(值為true表示按照訪問順序迭代,值為false表示按照插入順序迭代)
默認構造器accessOrder為false是按照插入順序迭代的
public LinkedHashMap() {
super();
accessOrder = false;
}
ConcurrentHashMap
ConcurrentHashMap是并發包下的類,屬于執行緒安全的HashMap,
java8中ConcurrentHashMap放棄了Segment分段加鎖的機制,采用了Node+CAS+Syncronized保證并發安全,
大量的采用了自旋+CAS操作
key和value都不可以為null,否則會拋出空指標例外
final V putVal(K key, V value, boolean onlyIfAbsent) {
if (key == null || value =https://www.cnblogs.com/life-time/archive/2021/01/27/= null) throw new NullPointerException();
int hash = spread(key.hashCode());
int binCount = 0;
for (Node[] tab = table;;) {
Node f; int n, i, fh;
if (tab == null || (n = tab.length) == 0)
tab = initTable();
else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) {
if (casTabAt(tab, i, null,
new Node(hash, key, value, null)))
break; // no lock when adding to empty bin
}
else if ((fh = f.hash) == MOVED)
tab = helpTransfer(tab, f);
else {
V oldVal = null;
synchronized (f) {
if (tabAt(tab, i) == f) {
if (fh >= 0) {
binCount = 1;
for (Node e = f;; ++binCount) {
K ek;
if (e.hash == hash &&
((ek = e.key) == key ||
(ek != null && key.equals(ek)))) {
oldVal = e.val;
if (!onlyIfAbsent)
e.val = value;
break;
}
Node pred = e;
if ((e = e.next) == null) {
pred.next = new Node(hash, key,
value, null);
break;
}
}
}
else if (f instanceof TreeBin) {
Node p;
binCount = 2;
if ((p = ((TreeBin)f).putTreeVal(hash, key,
value)) != null) {
oldVal = p.val;
if (!onlyIfAbsent)
p.val = value;
}
}
}
}
if (binCount != 0) {
if (binCount >= TREEIFY_THRESHOLD)
treeifyBin(tab, i);
if (oldVal != null)
return oldVal;
break;
}
}
}
addCount(1L, binCount);
return null;
}
HashMap和HashTable的區別
- HashMap執行緒不安全,HashTable執行緒安全
- HashMap性能比HashTable好
- HashMap鍵值允許為null,HashTable鍵值不允許為null
- HashMap繼承AbstractMap,HashTable繼承Dictionary類
- HashMap初始容量為16,HashTable初始容量為11
- HashMap擴容是翻一倍,HashTable是翻一倍+1
- HashMap的Iterator迭代器是fail-fast的,而HashTable的Enumerator是fail-safe的
由于本身的博客百度沒有收錄,博客地址http://zhhll.icu
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/253405.html
標籤:其他
