版權聲明:本文為部落客原創文章,未經部落客允許不得轉載。 https://blog.csdn.net/weixin_40254498/article/details/81780244
HashMap
基于哈希表的 Map 接口的實作。此實作提供所有可選的映射操作,并允許使用 null 值和 null 鍵。(除了非同步和允許使用 null 之外,HashMap 類與 Hashtable 大緻相同。)此類不保證映射的順序,特别是它不保證該順序恒久不變。 此實作假定哈希函數将元素适當地分布在各桶之間,可為基本操作(get 和 put)提供穩定的性能。疊代 collection 視圖所需的時間與 HashMap 執行個體的“容量”(桶的數量)及其大小(鍵-值映射關系數)成比例。是以,如果疊代性能很重要,則不要将初始容量設定得太高(或将加載因子設定得太低)。
資料結構
先看下hashmap的資料結構
大概就是如圖所示。
table就是數組咯。連結清單的他們稱之為桶。大于門檻值就轉成紅黑樹咯,主要是為了提高效率。
使用紅黑樹來實作。
構造方法
/**
* Constructs an empty <tt>HashMap</tt> with the specified initial
* capacity and load factor.
*
* @param initialCapacity the initial capacity
* @param loadFactor the load factor
* @throws IllegalArgumentException if the initial capacity is negative
* or the load factor is nonpositive
*/
public HashMap(int initialCapacity, float loadFactor) {
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal initial capacity: " +
initialCapacity);
if (initialCapacity > MAXIMUM_CAPACITY)
initialCapacity = MAXIMUM_CAPACITY;
if (loadFactor <= 0 || Float.isNaN(loadFactor))
throw new IllegalArgumentException("Illegal load factor: " +
loadFactor);
this.loadFactor = loadFactor;
this.threshold = tableSizeFor(initialCapacity);
}
/**
* Constructs an empty <tt>HashMap</tt> with the specified initial
* capacity and the default load factor (0.75).
*
* @param initialCapacity the initial capacity.
* @throws IllegalArgumentException if the initial capacity is negative.
*/
public HashMap(int initialCapacity) {
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
/**
* 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; // all other fields defaulted
}
/**
* Constructs a new <tt>HashMap</tt> with the same mappings as the
* specified <tt>Map</tt>. The <tt>HashMap</tt> is created with
* default load factor (0.75) and an initial capacity sufficient to
* hold the mappings in the specified <tt>Map</tt>.
*
* @param m the map whose mappings are to be placed in this map
* @throws NullPointerException if the specified map is null
*/
public HashMap(Map<? extends K, ? extends V> m) {
this.loadFactor = DEFAULT_LOAD_FACTOR;
putMapEntries(m, false);
}
其中最主要的是初始化的大小
還有初始化填充因子
static final float DEFAULT_LOAD_FACTOR = 0.75f;
HashMap的容量超過目前數組長度*加載因子,就會執行resize()算法
比如說向水桶中裝水,此時HashMap就是一個桶, 這個桶的容量就是加載容量,
而加載因子就是你要控制向這個桶中倒的水不超過水桶容量的比例,比如加載因子是0.75 ,
那麼在裝水的時候這個桶最多能裝到3/4 處,超過這個比例時,桶會自動擴容。
是以,這個桶最多能裝水 = 桶的容量 * 加載因子。
/**
* 擷取初始值,你輸入的初始值,不一定是初始化時所用的初始值。
* 為什麼初始值必須是2得倍數呢,下面代碼會給你解釋。
* Returns a power of two size for the given target capacity.
*/
static final int tableSizeFor(int cap) {
int n = cap - 1;
n |= n >>> 1;
n |= n >>> 2;
n |= n >>> 4;
n |= n >>> 8;
n |= n >>> 16;
return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
}
MAXIMUM_CAPACITY = 1<<30;
這樣得到的始終是你輸入初始值
小于最小的2的次幂,也就是說
比如你輸入
15 --->>16
29 --->>32
44 --->>64
重要函數
hash()
/**
* Computes key.hashCode() and spreads (XORs) higher bits of hash
* to lower. Because the table uses power-of-two masking, sets of
* hashes that vary only in bits above the current mask will
* always collide. (Among known examples are sets of Float keys
* holding consecutive whole numbers in small tables.) So we
* apply a transform that spreads the impact of higher bits
* downward. There is a tradeoff between speed, utility, and
* quality of bit-spreading. Because many common sets of hashes
* are already reasonably distributed (so don't benefit from
* spreading), and because we use trees to handle large sets of
* collisions in bins, we just XOR some shifted bits in the
* cheapest possible way to reduce systematic lossage, as well as
* to incorporate impact of the highest bits that would otherwise
* never be used in index calculations because of table bounds.
*/
static final int hash(Object key) {
int h;
// 這一頓操作大概的意思就是保留了高16位的值
// 其實低16位得值也保留了下來,隻要在做一次異或,值就變回來了
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
public V put(K key, V value) {}
/**
* Associates the specified value with the specified key in this map.
* If the map previously contained a mapping for the key, the old
* value is replaced.
*
* @param key key with which the specified value is to be associated
* @param value value to be associated with the specified key
* @return the previous value associated with <tt>key</tt>, or
* <tt>null</tt> if there was no mapping for <tt>key</tt>.
* (A <tt>null</tt> return can also indicate that the map
* previously associated <tt>null</tt> with <tt>key</tt>.)
*/
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
/**
* Implements Map.put and related methods
*
* @param hash hash for key
* @param key the key
* @param value the value to put
* @param onlyIfAbsent if true, don't change existing value
* @param evict if false, the table is in creation mode.
* @return previous value, or null if none
*/
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
// table未初始化或者長度為0,進行擴容
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
// 看下值放在哪一個table[]
// 這裡也有一個為什麼table的大小為什麼必須是2的倍數的原因
// n 是 tab的長度 那麼 (n - 1) & hash 的意思就是?
// 假如 長度為 16(10000) 那麼 15(01111) & 就得到最後hash值相當于 h & (length - 1) == h % length
// 這樣數組也不會越界等 運算得比%運算得快
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
// 已經有了,就看下是放在 連結清單還是紅黑樹。
else {
Node<K,V> e; K k;
//先比較s是不是在頭節點
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 {
for (int binCount = 0; ; ++binCount) {
//直接放在尾部
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
//連結清單大于8個門檻值直接轉成紅黑樹
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
//存在一模一樣的key則跳出繼續
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 = e.value;
// onlyIfAbsent為false或者舊值為null
// onlyIfAbsent是傳入的參數 預設w為false直接替換
if (!onlyIfAbsent || oldValue == null)
//用新值替換舊值
e.value = value;
afterNodeAccess(e);
// 傳回舊值
return oldValue;
}
}
++modCount;
// 實際大小大于門檻值則擴容
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
public V get(Object key) {}
相對于put,get就比較簡單了。
相對jdk1.7版本
1.7 ---->1.8
位桶+連結清單 ----> 位桶+連結清單大于門檻值(8)後切換成紅黑樹
大資料下 O(n)->>O(Logn)
/**
* Returns the value to which the specified key is mapped,
* or {@code null} if this map contains no mapping for the key.
*
* <p>More formally, if this map contains a mapping from a key
* {@code k} to a value {@code v} such that {@code (key==null ? k==null :
* key.equals(k))}, then this method returns {@code v}; otherwise
* it returns {@code null}. (There can be at most one such mapping.)
*
* <p>A return value of {@code null} does not <i>necessarily</i>
* indicate that the map contains no mapping for the key; it's also
* possible that the map explicitly maps the key to {@code null}.
* The {@link #containsKey containsKey} operation may be used to
* distinguish these two cases.
*
* @see #put(Object, Object)
*/
public V get(Object key) {
Node<K,V> e;
return (e = getNode(hash(key), key)) == null ? null : e.value;
}
/**
* Implements Map.get and related methods
*
* @param hash hash for key
* @param key the key
* @return the node, or null if none
*/
final Node<K,V> getNode(int hash, Object key) {
Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
// table已經初始化,長度大于0,根據hash尋找table中的項也不為空
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & hash]) != null) {
//判斷是不是第一個結點 是就傳回
if (first.hash == hash && // always check first node
((k = first.key) == key || (key != null && key.equals(k))))
return first;
// 節點下面還有東西?
if ((e = first.next) != null) {
// 是紅黑樹嗎?
if (first instanceof TreeNode)
return ((TreeNode<K,V>)first).getTreeNode(hash, key);
//不是紅黑樹那你肯定是連結清單咯
do {
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
return null;
}
resize()
hashmap的擴容方法
/**
* Initializes or doubles table size. If null, allocates in
* accord with initial capacity target held in field threshold.
* Otherwise, because we are using power-of-two expansion, the
* elements from each bin must either stay at same index, or move
* with a power of two offset in the new table.
*
* @return the table
*/
final Node<K,V>[] resize() {
//儲存舊的
Node<K,V>[] oldTab = table;
//儲存長度
int oldCap = (oldTab == null) ? 0 : oldTab.length;
//儲存門檻值 需要resize的門檻值
int oldThr = threshold;
int newCap, newThr = 0;
// 之前table大小大于0
if (oldCap > 0) {
// 之前table大于最大容量
if (oldCap >= MAXIMUM_CAPACITY) {
// 門檻值為最大整形
threshold = Integer.MAX_VALUE;
return oldTab;
}
// 容量翻倍,使用左移,效率更高
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
// double threshold 門檻值翻倍
newThr = oldThr << 1;
// 之前門檻值大于0
else if (oldThr > 0) // initial capacity was placed in threshold
newCap = oldThr;
// oldCap = 0并且oldThr = 0,使用預設值(如使用HashMap()構造函數,之後再插入一個元素會調用resize函數,會進入這一步)
else { // zero initial threshold signifies using defaults
newCap = DEFAULT_INITIAL_CAPACITY;
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
}
// 新門檻值為0
if (newThr == 0) {
float ft = (float)newCap * loadFactor;
newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
(int)ft : Integer.MAX_VALUE);
}
threshold = newThr;
@SuppressWarnings({"rawtypes","unchecked"})
// 初始化table
Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
table = newTab;
// 之前的table已經初始化過
if (oldTab != null) {
// 複制元素,重新進行hash
for (int j = 0; j < oldCap; ++j) {
Node<K,V> e;
if ((e = oldTab[j]) != null) {
oldTab[j] = null;
//如果連結清單隻有一個,則直接指派
if (e.next == null)
newTab[e.hash & (newCap - 1)] = e;
//紅黑樹啊
else if (e instanceof TreeNode)
((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
//隻能是連結清單了
else { // preserve order
Node<K,V> loHead = null, loTail = null;
Node<K,V> hiHead = null, hiTail = null;
Node<K,V> next;
do {
next = e.next;
if ((e.hash & oldCap) == 0) {
if (loTail == null)
loHead = e;
else
loTail.next = e;
loTail = e;
}
else {
if (hiTail == null)
hiHead = e;
else
hiTail.next = e;
hiTail = e;
}
} while ((e = next) != null);
if (loTail != null) {
loTail.next = null;
newTab[j] = loHead;
}
if (hiTail != null) {
hiTail.next = null;
newTab[j + oldCap] = hiHead;
}
}
}
}
}
return newTab;
}
這一頓操作之後大概就是這個過程吧
END
HashMap運用了許多非常巧妙的算法吧,大量的使用到了位運算,讓這個結構運作更穩定更巧妙。每次看都有新收獲。