Java集合三大致系——List、Set、Map,而Set是基於Map實現的.在Map中HashMap做爲其中經常使用類,面試中的常客.記得以前有次面試回答,HashMap是鏈表散列的數據結構,其容量是16,負載因子0.75,當大於容量*負載因子會進行2倍擴容,put操做是將key的hashcode值進行一次hash計算,key的equals方法找到鍵值對進行替換返回被舊數據,若沒有找到會插入到鏈表中,HashMap線程不安全.當面試官聽到這些之後第一個問題爲何容量是16,1五、14不行嗎?爲何2倍擴容?爲何HashMap建議不可變對象用Key?本身當時思考得不夠深刻,還沒問到ConcurrentHashMap我就已經心慌了...下面我來聊一聊我對HashMap的見解html
先看下HashMap的繼承關係:
java
static class Entry implements Map.Entry {
/** 賤對象*/
final K key;
/** 值對象*/
V value;
/** 指向下一個Entry對象*/
Entry next;
/** 鍵對象哈希值*/
int hash;
}
複製代碼
/**
* 默認初始容量16——必須是2的冪
*/
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;
/**
* HashMap存儲的鍵值對數量
*/
transient int size;
/**
* 默認負載因子0.75
*/
static final float DEFAULT_LOAD_FACTOR = 0.75f;
/**
* 擴容閾值,當size大於等於其值,會執行resize操做
* 通常狀況下threshold=capacity*loadFactor
*/
int threshold;
/**
* Entry數組
*/
transient Entry[] table = (Entry[]) EMPTY_TABLE;
/**
* 記錄HashMap修改次數,fail-fast機制
*/
transient int modCount;
/**
* hashSeed用於計算key的hash值,它與key的hashCode進行按位異或運算
* hashSeed是一個與實例相關的隨機值,用於解決hash衝突
* 若是爲0則禁用備用哈希算法
*/
transient int hashSeed = 0;
複製代碼
/**
* 指定容量及負載因子構造方法
*/
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;
//設置擴容閾值
threshold = initialCapacity;
//空方法,讓其子類重寫例如LinkedHashMap
init();
}
/**
* 默認構造方法,採用默認容量16,默認負載因子0.75
*/
public HashMap() {
this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR);
}
/**
* 指定容量構造方法,負載因子默認0.75
*/
public HashMap(int initialCapacity) {
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
複製代碼
從這3個構造方法中咱們能夠發現雖然指定了初始化容量大小,但此時的table仍是空,是一個空數組,且擴容閾值爲初始容量.在其put操做前,會建立數組.node
/**
* 根據已有Map構造新HashMap的構造方法
* 初始容量:參數map大小除以默認負載因子+1與默認容量的最大值
* 初始負載因子:默認負載因子0.75
*/
public HashMap(Map m) {
this(Math.max((int) (m.size() / DEFAULT_LOAD_FACTOR) + 1,
DEFAULT_INITIAL_CAPACITY), DEFAULT_LOAD_FACTOR);
inflateTable(threshold);
//把傳入的map裏的全部元素放入當前已構造的HashMap中
putAllForCreate(m);
}
複製代碼
這個構造方法即是在put操做前調用inflateTable方法,inflate意爲膨脹,這個方法咱們來看下,注意剛也提到了此時的threshold擴容閾值是初始容量面試
private void inflateTable(int toSize) { //返回不小於number的最小的2的冪數,最大爲MAXIMUM_CAPACITY int capacity = roundUpToPowerOf2(toSize); //設置擴容閾值,值爲容量*負載因子與最大容量+1的較小值 threshold = (int) Math.min(capacity * loadFactor,
MAXIMUM_CAPACITY + 1); //建立數組 table = new Entry[capacity]; //初始化HashSeed值 initHashSeedAsNeeded(capacity); } /** * 返回不小於number的最小的2的冪數,最大爲MAXIMUM_CAPACITY */ private static int roundUpToPowerOf2(int number) { // assert number >= 0 : "number must be non-negative"; /** * 若number不小於最大容量則爲最大容量 * 若number小於最大容量大於1,則爲不小於number的最小的2的冪數 * 若都不是則爲1 */ return number >= MAXIMUM_CAPACITY ? MAXIMUM_CAPACITY : (number > 1) ? Integer.highestOneBit((number - 1) << 1) : 1; } 複製代碼
從這裏咱們能夠到HashMap建立了一個2的冪數容量的數組,那爲何必定要這樣設計?後面我會介紹.算法
我往HashMap中添加元素調用最多就是這個put方法
public V put(K key, V value)
咱們來看下其代碼實現:
shell
public V put(K key, V value) {
//若數組爲空時建立數組
if (table == EMPTY_TABLE) {
inflateTable(threshold);
}
//若key爲null
if (key == null)
return putForNullKey(value);
//對key進行hash計算,獲取hash值
int hash = hash(key);
//根據剛獲得的hash值與數組長度計算桶位置
int i = indexFor(hash, table.length);
//遍歷桶中鏈表
for (Entry e = table[i]; e != null; e = e.next) {
Object k;
//key值與hash值都相同的話進行替換
if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
V oldValue = e.value;
e.value = value;
//空方法,讓其子類重寫例如LinkedHashMap
e.recordAccess(this);
//返回舊值
return oldValue;
}
}
//記錄修改
modCount++;
//鏈表中不存在此鍵,則調用addEntry方法向鏈表中添加新結點
addEntry(hash, key, value, i);
return null;
}
複製代碼
從上面的源碼咱們能夠看到:
①HashMap首先判斷數組是否爲空,若爲空調用inflateTable進行擴容.
②接着判斷key是否爲null,若爲null就調用putForNullKey方法進行put.因此HashMap容許Key爲null
③再將key進行一次哈希計算,獲得的哈希值和當前數組長度計算獲得數組中的索引
④而後遍歷該數組索引下的鏈表,若key的hash和傳入key的hash相同且key的equals放回true,那麼直接覆蓋 value
⑤最後若不存在,那麼在此鏈表中頭插建立新結點
api
逐步來介紹(第一步就不說了上文已闡述過),第二步最主要就是putForNullKey方法,從中咱們能夠發現若key爲null會先從0位置桶上鍊表遍歷,若找到結點key爲null的進行替換,不存在則添加結點.方法內的addEntry後續講數組
private V putForNullKey(V value) {
//遍歷0位置桶上的鏈表,若存在結點Entry的key爲null替換value,返回舊值
for (Entry e = table[0]; e != null; e = e.next) {
if (e.key == null) {
V oldValue = e.value;
e.value = value;
e.recordAccess(this);
return oldValue;
}
}
modCount++;
//若不存在,0位置桶上的鏈表中添加新結點
addEntry(0, null, value, 0);
return null;
}
複製代碼
第三步中先看下HashMap的hash算法,獲取鍵對象哈希值並將補充哈希函數應用於該對象結果哈希,防止質量差的哈希函數,注意:空鍵老是映射到散列0,所以索引爲0,1.8的hash方法已進行過優化,安全
final int hash(Object k) {
// 當h不爲0且鍵對象類型爲String用此算法,1.8已刪除
int h = hashSeed;
if (0 != h && k instanceof String) {
return sun.misc.Hashing.stringHash32((String) k);
}
h ^= k.hashCode();
//此函數確保在每一個比特位置上僅以恆定倍數不一樣的hashCode具備有限的碰撞數量(在默認負載因子下約爲8)
h ^= (h >>> 20) ^ (h >>> 12);
return h ^ (h >>> 7) ^ (h >>> 4);
}
複製代碼
根據所計算的值與數組長度計算桶位置:數據結構
static int indexFor(int h, int length) {
return h & (length-1);
}
複製代碼
此方法對數組的長度取模運算,獲得的餘數進行下表訪問,那麼既然是取模運算爲何不直接h%length,由於其效率很低,因此採用位運算.從中咱們能夠看出,假設length爲16,當咱們h爲1,17時算出桶的索引都爲1這種狀況就稱爲衝突(k1≠k2,而f(k1)=f(k2)).當有衝突時HashMap採用鏈地址法(把全部的同義詞用單鏈錶鏈接起來的方法)處理衝突
其次假設length分別爲16,15,14時,他們的衝突次數:
length = 16 | length = 15 | length = 14 | ||||||
h | h&length-1 | 結果 | h&length-1 | 結果 | h&length-1 | 結果 | ||
0 | 0000 & 1111 | 0000 | 0 | 0000 & 1110 | 0000 | 0000 & 1101 | 0000 | |
1 | 0001 & 1111 | 0001 | 1 | 0001 & 1110 | 0000 | 0001 & 1101 | 0001 | |
2 | 0010 & 1111 | 0010 | 2 | 0010 & 1110 | 0010 | 0010 & 1101 | 0000 | |
3 | 0011 & 1111 | 0011 | 3 | 0011 & 1110 | 0010 | 0011 & 1101 | 0001 | |
4 | 0100 & 1111 | 0100 | 4 | 0100 & 1110 | 0100 | 0100 & 1101 | 0100 | |
5 | 0101 & 1111 | 0101 | 5 | 0101 & 1110 | 0100 | 0101 & 1101 | 0101 | |
6 | 0110 & 1111 | 0110 | 6 | 0110 & 1110 | 0110 | 0110 & 1101 | 0100 | |
7 | 0111 & 1111 | 0111 | 7 | 0111 & 1110 | 0110 | 0111 & 1101 | 0101 | |
8 | 1000 & 1111 | 1000 | 8 | 1000 & 1110 | 1000 | 1000 & 1101 | 1000 | |
9 | 1001 & 1111 | 1001 | 9 | 1001 & 1110 | 1000 | 1001 & 1101 | 1001 | |
10 | 1010 & 1111 | 1010 | 10 | 1010 & 1110 | 1010 | 1010 & 1101 | 1000 | |
11 | 1011 & 1111 | 1011 | 11 | 1011 & 1110 | 1010 | 1011 & 1101 | 1001 | |
12 | 1100 & 1111 | 1100 | 12 | 1100 & 1110 | 1100 | 1100 & 1101 | 1100 | |
13 | 1101 & 1111 | 1101 | 13 | 1101 & 1110 | 1100 | 1101 & 1101 | 1101 | |
14 | 1110 & 1111 | 1110 | 14 | 1110 & 1110 | 1110 | 1110 & 1101 | 1100 | |
15 | 1111 & 1111 | 1111 | 15 | 1111 & 1110 | 1110 | 1111 & 1101 | 1101 | |
0個衝突 | 8個衝突 | 8個衝突 |
第四步中若key的hash和傳入key的hash相同且key的equals放回true,那麼直接覆蓋value.key的hash值是根據其hashcode值進行hash哈希計算獲得的,那麼當咱們用可變對象時其hashcode值很容易會變化,那麼就會帶來風險找不到原來的value,因此HashMap建議使用不可變對象做爲Key
最後一步addEntry方法建立新結點,代碼以下
void addEntry(int hash, K key, V value, int bucketIndex) {
//當前hashmap中的鍵值對數量超過擴容閾值,進行2倍擴容
if ((size >= threshold) && (null != table[bucketIndex])) {
//2倍擴容
resize(2 * table.length);
//擴容後,桶的數量增長了,從新對鍵進行哈希碼的計算
hash = (null != key) ? hash(key) : 0;
//根據鍵的新哈希碼和新的桶數量從新計算桶索引值
bucketIndex = indexFor(hash, table.length);
}
//建立結點
createEntry(hash, key, value, bucketIndex);
}
/**
* 頭插結點
* 將本來在數組中存放的鏈表頭置入到新的Entry以後,將新的Entry放入數組中
*/
void createEntry(int hash, K key, V value, int bucketIndex) {
Entry e = table[bucketIndex];
table[bucketIndex] = new Entry<>(hash, key, value, e);
size++;
}
複製代碼
先不看擴容狀況,當不須要擴容時,hashmap採用頭插法插入結點,爲何要頭插而不是尾插,由於後插入的數據被使用的頻次更高,而單鏈表沒法隨機訪問只能從頭開始遍歷查詢,因此採用頭插.忽然又想爲何不採用二維數組的形式利用線性探查法來處理衝突,數組末尾插入也是O(1),可數組其最大缺陷就是在於若不是末尾插入刪除效率很低,其次若添加的數據分佈均勻那麼每一個桶上的數組都須要預留內存.
再來看看擴容:
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];
//將舊Entry數組轉移到新Entry數組中去
transfer(newTable, initHashSeedAsNeeded(newCapacity));
table = newTable;
//從新設置擴容閾值
threshold = (int)Math.min(newCapacity * loadFactor, MAXIMUM_CAPACITY + 1);
}
複製代碼
transfer方法遍歷舊數組全部Entry,根據新的容量逐個從新計算索引頭插保存在新數組中,擴容至關麻煩,因此若是當咱們知道須要添加多少數據時最好指定容量初始化.
/**
* 將舊Entry數組轉移到新Entry數組中去
*/
void transfer(Entry[] newTable, boolean rehash) {
//獲取新數組的長度
int newCapacity = newTable.length;
for (Entry e : table) {
while(null != e) {
Entry next = e.next;
if (rehash) {
e.hash = null == e.key ? 0 : hash(e.key);
}
//從新計算索引
int i = indexFor(e.hash, newCapacity);
e.next = newTable[i];
newTable[i] = e;
e = next;
}
}
}
複製代碼
在這裏可能會出現環形鏈表致使死循環.先假設容量爲4,負載因子默認0.75,擴容閾值3,HashMap當前存儲以下:
另外這讓我想起一道經典面試題鏈表反轉,本身動手實現了下
public class Node {
private Node next;
private Object item;
public Node(Object item, Node next) {
this.item = item;
this.next = next;
}
public static Node get(){
Node last = new Node(6, null);
Node fifth = new Node(5,last);
Node fourth = new Node(4, fifth);
Node third = new Node(3, fourth);
Node second = new Node(2, third);
Node first = new Node(1, second);
return first;
}
public static void outPut(Node node){
while(node != null){
System.out.print(node.item);
node = node.next;
}
}
public static Node reverse(Node node){
Node newNode = node;
Node temp = null;
while (node != null && node.next != null){
Node next = node.next;
node.next = temp;
temp = node;
newNode = new Node(next.item, node);
node = next;
}
return newNode;
}
public static void main(String[] args) {
Node first = get();//獲取單鏈表頭結點
outPut(first);//輸出整條鏈表數據
first = reverse(first);
outPut(first);
}
}
複製代碼
知道了put原理,get操做就很好理解了,先看下代碼:
/**
* 返回到指定鍵所映射的值,若不存在返回null
*/
public V get(Object key) {
//與put同樣單獨處理
if (key == null)
return getForNullKey();
Entry entry = getEntry(key);
return null == entry ? null : entry.getValue();
}
複製代碼
與存null key同樣,從0位置上的桶上獲取
private V getForNullKey() {
if (size == 0) {
return null;
}
for (Entry e = table[0]; e != null; e = e.next) {
if (e.key == null)
return e.value;
}
return null;
}
複製代碼
getEntry
final Entry getEntry(Object key) {
//size爲0,即hashmap爲空,返回null
if (size == 0) {
return null;
}
//對key進行hash計算,獲取hash值
int hash = (key == null) ? 0 : hash(key);
//根據hash值與數組長度獲取桶位置,遍歷對應桶上鍊表
for (Entry e = table[indexFor(hash, table.length)];
e != null;
e = e.next) {
Object k;
//key值與hash值都相同的話返回結點
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
}
//若不存在返回null
return null;
}
複製代碼
本篇主要圍繞着java7HashMap源碼講解其原理作個小結:
①由於其put操做對key爲null場景作了單獨處理,因此HashMap容許null做爲Key
②由於HashMap在算桶index時根據key的hashcode值進行hash計算獲取hash值與數組length-1進行與運算,length-1的二進制位全爲1,這樣能夠分佈均勻避免衝突,因此HashMap容量要爲2的冪數
③由於HashMap的操做會圍繞key的hashcode進行hash計算,而可變對象其hashcode很容易變化,因此HashMap建議用不可變對象做爲Key.
④HashMap線程不安全擴容方法可能會致使環形鏈表死循環,因此若須要多線程場景下操做可使用ConcurrentHashMap
⑤.當發生衝突時,HashMap採用鏈地址法(拉鍊法)處理衝突,而後根據key的hash以及equals方法具體獲取key所對應的Entry
⑥.爲何HashMap初始容量定爲16,我認爲如果8的話擴容閾值爲6,沒放幾個就會擴容;而32的話又不會放那麼多,資源浪費
https://coolshell.cn/articles/9606.html http://www.cnblogs.com/chenssy/p/3521565.html