關於做者java
郭孝星,程序員,吉他手,主要從事Android平臺基礎架構方面的工做,歡迎交流技術方面的問題,能夠去個人Github提issue或者發郵件至guoxiaoxingse@163.com與我交流。git
文章目錄` 程序員
更多文章:github.com/guoxiaoxing…github
散列是一種對信息的處理方法,經過特定的算法將要檢索的項與用來檢索的索引(散列值)關聯起來,生成一種便於搜索的數據結構散列表。算法
散列的應用數組
咱們主要來討論散列表的應用,散列值也即哈希值,提到哈希值,咱們不由會聯想到Java裏到hashCode()方法與equals()方法。安全
hashCode()方法返回該對象的哈希碼值,在一次Java應用運行期間,若是該對象上equals()方法裏比較的信息沒有修改,則對該對象屢次調用hashCode()方法時返回
相同的整數。數據結構
從這個定義咱們能夠了解到如下幾點:架構
咱們再重寫hashCode()方法時,一般用如下方式來計算hashCode:app
1 將一個非0的常數值保存到一個名爲result的int型變量中。
2 分別計算每一個域的散列碼並相加求和,散列碼的生成規則以下:
經過上面的描述,咱們能夠知道散列表主要面臨的問題是散列值均勻的分佈,而咱們主要解決的問題是在散列值在計算的時候出現的衝突問題,即出現
了兩個相同的散列值,一般這也成爲哈希衝突。Java在解決哈希衝突上,使用了一種叫作分離連接法的方法。
分離連接法將擁有相同哈希值的全部元素保存到同一個單向鏈表中,因此這種散列表總體上是一個數組,數組裏面存放的元素時單向鏈表。
這樣方法有個叫負載因子的概念,負載因子 = 元素個數 / 散列表大小.
負載因子是空間利用率與查找效率的一種平衡。
Java集合裏的HashMap就使用了這種方法,咱們會在下面的HashMap源碼分析了詳細討論這種方法的實現。
HashMap基於數組實現,數組裏的元素是一個單向鏈表。
HashMap具備如下特色:
HashMap實現瞭如下接口:
//初始同樂,初始容量必須爲2的n次方
static final int DEFAULT_INITIAL_CAPACITY = 4;
//最大容量爲2的30次方
static final int MAXIMUM_CAPACITY = 1 << 30;
//默認負載因子爲0.75f
static final float DEFAULT_LOAD_FACTOR = 0.75f;
//默認的空表
static final HashMapEntry<?,?>[] EMPTY_TABLE = {};
//存儲元素的表
transient HashMapEntry<K,V>[] table = (HashMapEntry<K,V>[]) EMPTY_TABLE;
//集合大小
transient int size;
//下次擴容閾值,size > threshold就會進行擴容,擴容閾值 = 容量 * 負載因子。
int threshold;
//加載所以
final float loadFactor = DEFAULT_LOAD_FACTOR;
//修改次數
transient int modCount;複製代碼
從這個結構transient HashMapEntry[] table = (HashMapEntry[]) EMPTY_TABLE能夠看出,HashMap基於數組實現,數組裏的元素是一個單向鏈表。
HashMap使用哈希算法將key散列成一個int值,這個值就對應了這個數組的下標,因此你能夠知道,若是兩個key的哈希值相等,則它們會被放在當前下表的單向鏈表中。
這裏咱們着重介紹一下負載因子,它是空間利用率與查找效率的一種平衡。
static class HashMapEntry<K,V> implements Map.Entry<K,V> {
//鍵
final K key;
//值
V value;
//後繼的引用
HashMapEntry<K,V> next;
//哈希值
int hash;
HashMapEntry(int h, K k, V v, HashMapEntry<K,V> n) {
value = v;
next = n;
key = k;
hash = h;
}
public final K getKey() {
return key;
}
public final V getValue() {
return value;
}
public final V setValue(V newValue) {
V oldValue = value;
value = newValue;
return oldValue;
}
public final boolean equals(Object o) {
if (!(o instanceof Map.Entry))
return false;
Map.Entry e = (Map.Entry)o;
Object k1 = getKey();
Object k2 = e.getKey();
if (k1 == k2 || (k1 != null && k1.equals(k2))) {
Object v1 = getValue();
Object v2 = e.getValue();
if (v1 == v2 || (v1 != null && v1.equals(v2)))
return true;
}
return false;
}
public final int hashCode() {
return Objects.hashCode(getKey()) ^ Objects.hashCode(getValue());
}
public final String toString() {
return getKey() + "=" + getValue();
}
//當向HashMao裏添加元素時調用此方法,這裏提供給子類實現
void recordAccess(HashMap<K,V> m) {
}
//當從HashM裏刪除元素時調用此方法,這裏提供給子類實現
void recordRemoval(HashMap<K,V> m) {
}
}複製代碼
HashMapEntry用來描述HashMao裏的元素,它保存了鍵、值、後繼的引用與哈希值。
//提供初始容量和負載因子進行構造
public HashMap(int initialCapacity, float loadFactor) {
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal initial capacity: " +
initialCapacity);
if (initialCapacity > MAXIMUM_CAPACITY) {
initialCapacity = MAXIMUM_CAPACITY;
} else if (initialCapacity < DEFAULT_INITIAL_CAPACITY) {
initialCapacity = DEFAULT_INITIAL_CAPACITY;
}
if (loadFactor <= 0 || Float.isNaN(loadFactor))
throw new IllegalArgumentException("Illegal load factor: " +
loadFactor);
// Android-Note: We always use the default load factor of 0.75f.
// This might appear wrong but it's just awkward design. We always call
// inflateTable() when table == EMPTY_TABLE. That method will take "threshold"
// to mean "capacity" and then replace it with the real threshold (i.e, multiplied with
// the load factor).
threshold = initialCapacity;
init();
}
//提供初始容量進行構造
public HashMap(int initialCapacity) {
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
//空構造方法
public HashMap() {
this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR);
}
//提供一個Map進行構造
public HashMap(Map<? extends K, ? extends V> m) {
this(Math.max((int) (m.size() / DEFAULT_LOAD_FACTOR) + 1,
DEFAULT_INITIAL_CAPACITY), DEFAULT_LOAD_FACTOR);
inflateTable(threshold);
putAllForCreate(m);
}複製代碼
public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable, Serializable{
public V put(K key, V value) {
if (table == EMPTY_TABLE) {
inflateTable(threshold);
}
if (key == null)
//若是key爲null,則將其放在table[0]的位置
return putForNullKey(value);
//根據key計算hash值
int hash = sun.misc.Hashing.singleWordWangJenkinsHash(key);
//根據hash值和數組容量,找到索引值
int i = indexFor(hash, table.length);
//遍歷table[i]位置的鏈表,查找相同的key,若找到則則用新的value替換掉oldValue
for (HashMapEntry<K,V> 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;
}
}
modCount++;
//若沒有查找到相同的key,則添加key到table[i]位置,新添加的元素老是添加在單向鏈表的表頭位置,後面的元素稱爲它的後繼
addEntry(hash, key, value, i);
return null;
}
//根據哈希值與數組容量計算索引位置,使用&代替取模,提高效率。
static int indexFor(int h, int length) {
// assert Integer.bitCount(length) == 1 : "length must be a non-zero power of 2";
return h & (length-1);
}
void addEntry(int hash, K key, V value, int bucketIndex) {
//若是達到了擴容閾值,則進行擴容,容量翻倍
if ((size >= threshold) && (null != table[bucketIndex])) {
resize(2 * table.length);
hash = (null != key) ? sun.misc.Hashing.singleWordWangJenkinsHash(key) : 0;
bucketIndex = indexFor(hash, table.length);
}
createEntry(hash, key, value, bucketIndex);
}
//新添加的元素老是添加在單向鏈表的表頭位置,後面的元素稱爲它的後繼
void createEntry(int hash, K key, V value, int bucketIndex) {
HashMapEntry<K,V> e = table[bucketIndex];
table[bucketIndex] = new HashMapEntry<>(hash, key, value, e);
size++;
}
}複製代碼
這個添加的流程仍是比較簡單的,這個流程以下:
這裏你能夠看到HashMap使用了咱們上面所說的分離連接法來解決哈希衝突的問題。
public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable, Serializable{
public V remove(Object key) {
Entry<K,V> e = removeEntryForKey(key);
return (e == null ? null : e.getValue());
}
final Entry<K,V> removeEntryForKey(Object key) {
if (size == 0) {
return null;
}
//計算哈希值,根據哈希值與數組容量計算它所在的索引,根據索引查找它所在的鏈表
int hash = (key == null) ? 0 : sun.misc.Hashing.singleWordWangJenkinsHash(key);
int i = indexFor(hash, table.length);
HashMapEntry<K,V> prev = table[i];
HashMapEntry<K,V> e = prev;
//從起始節點開始遍歷,查找要刪除的元素,刪除該節點,將節點的後繼添加爲它前驅的後繼
while (e != null) {
HashMapEntry<K,V> 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;
}
}複製代碼
刪除的流程以下所示:
public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable, Serializable{
public V get(Object key) {
if (key == null)
return getForNullKey();
Entry<K,V> entry = getEntry(key);
return null == entry ? null : entry.getValue();
}
final Entry<K,V> getEntry(Object key) {
if (size == 0) {
return null;
}
//計算哈希值,根據哈希值與數組容量計算它所在的索引,根據索引查找它所在的鏈表
int hash = (key == null) ? 0 : sun.misc.Hashing.singleWordWangJenkinsHash(key);
//在單向鏈表中查找該元素
for (HashMapEntry<K,V> 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;
}
}複製代碼
查找的流程也十分簡單,具體以下: