HASH表原理
大家都知道,在所有的線性數據結構中,數組的定位速度最快,因為它可通過數組下標直接定位到相應的數組空間,就不需要一個個查找。而哈希表就是利用數組這個能夠快速定位數據的結構解決以上的問題的。
具體如何做呢?大家是否有注意到前面說的話:“數組可以通過下標直接定位到相應的空間”,對就是這句,哈希表的做法其實很簡單,就是把Key通過一個固定的算法函數既所謂的哈希函數轉換成一個整型數字,然后就將該數字對數組長度進行取余,取余結果就當作數組的下標,將value存儲在以該數字為下標的數組空間里,而當使用哈希表進行查詢的時候,就是再次使用哈希函數將key轉換為對應的數組下標,並定位到該空間獲取value,如此一來,就可以充分利用到數組的定位性能進行數據定位。
不知道說到這里,一些不了解的朋友是否大概了解了哈希表的原理,其實就是通過空間換取時間的做法。到這里,可能有的朋友就會問,哈希函數對key進行轉換,取余的值一定是唯一的嗎?這個當然不能保證,主要是由於hashcode會對數組長度進行取余,因此其結果由於數組長度的限制必然會出現重復,所以就會有“沖突”這一問題,至於解決沖突的辦法其實有很多種,比如重復散列的方式,大概就是定位的空間已經存在value且key不同的話就重新進行哈希加一並求模數組元素個數,既 (h(k)+i) mod S , i=1,2,3…… ,直到找到空間為止。還有其他的方式大家如果有興趣的話可以自己找找資料看看。
在java.util.HashMap中的關鍵代碼:
Entry[] table;
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);
}
/**
* Returns index for hash code h.
*/
static int indexFor(int h, int length) {
return h & (length-1);
}
final Entry<K,V> getEntry(Object key) {
int hash = (key == null) ? 0 : hash(key.hashCode());
for (Entry<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;
}
public V put(K key, V value) {
if (key == null)
return putForNullKey(value);
int hash = hash(key.hashCode());
int i = indexFor(hash, table.length);
for (Entry<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++;
addEntry(hash, key, value, i);
return null;
}
void addEntry(int hash, K key, V value, int bucketIndex) {
Entry<K,V> e = table[bucketIndex];
table[bucketIndex] = new Entry<K,V>(hash, key, value, e);
if (size++ >= threshold)
resize(2 * table.length);
}