眾所周知,使用Java的HashMap數(shù)據(jù)結(jié)構(gòu)時(shí),要求正確實(shí)現(xiàn)hashCode(),但是為什么呢?hashCode產(chǎn)生的散列碼到底代表什么,其在HashMap中到底有何作用?本文將為您詳細(xì)道來。
1 為什么要用散列值?
我們已經(jīng)知道如果不能正確覆蓋hashCode和equal方法,就不能正確使用散列數(shù)據(jù)結(jié)構(gòu)(HashSet,HashMap, LinkedMashSet, LinkedMashMap)。
使用Map這種數(shù)據(jù)結(jié)構(gòu),最重要的應(yīng)用場景就是維系“Key-Value”關(guān)系,通過key值能找到對應(yīng)的value。要實(shí)現(xiàn)Map的功能并不難,以下是《Thinking in Java》中利用兩個(gè)List實(shí)現(xiàn)Map的例子,
public class SlowMap<K,V> extends AbstractMap<K,V> {
private List<K> keys = new ArrayList<K>();
private List<V> values = new ArrayList<V>();
public V put(K key, V value) {
V oldValue = get(key); // The old value or null
if(!keys.contains(key)) {
keys.add(key);
values.add(value);
} else
values.set(keys.indexOf(key), value);
return oldValue;
}
public V get(Object key) { // key is type Object, not K
if(!keys.contains(key))
return null;
return values.get(keys.indexOf(key));
}
public Set<Map.Entry<K,V>> entrySet() {
Set<Map.Entry<K,V>> set= new HashSet<Map.Entry<K,V>>();
Iterator<K> ki = keys.iterator();
Iterator<V> vi = values.iterator();
while(ki.hasNext())
set.add(new MapEntry<K,V>(ki.next(), vi.next()));
return set;
}
public static void main(String[] args) {
SlowMap<String,String> m= new SlowMap<String,String>();
m.putAll(Countries.capitals(15));
System.out.println(m);
System.out.println(m.get("BULGARIA"));
System.out.println(m.entrySet());
}
}
這個(gè)SlowMap是線性存儲(chǔ),key沒有按照任何特定的順序保存,而是簡單粗暴的直接按存儲(chǔ)順序存儲(chǔ),這種作的結(jié)果就是要查詢key就必須線性查詢,但是線性查詢是最慢的查詢方式。
為了讓查詢key的效率更高,有一種方法就是保持key值的排序狀態(tài),然后使用Collection.binarySearch方法來進(jìn)行查找,但是這個(gè)樣還不夠滿足所有使用情況,需要更進(jìn)一步的突破。
2 為速度而生的散列碼:
想一想,什么樣的數(shù)據(jù)結(jié)構(gòu)獲取其中元素的速度最快?沒錯(cuò)就是數(shù)組(時(shí)間復(fù)雜度為O(1)),但是數(shù)組的最大問題在于其容量是固定的,面對可能是不固定數(shù)量的數(shù)據(jù)該怎么辦呢?想ArrayList那樣擴(kuò)容,如果擴(kuò)容太頻繁,數(shù)據(jù)結(jié)構(gòu)維護(hù)的代價(jià)就太大了。
為了解決這個(gè)矛盾,數(shù)組中并不直接保存key值,而是保存由key生成的標(biāo)識(shí),這個(gè)標(biāo)識(shí)可以在一定程度上代表key的信息,這就是散列碼,以散列碼為數(shù)組的下標(biāo)。由key值生成散列碼的過程被稱為散列函數(shù)。
散列函數(shù)在設(shè)計(jì)時(shí)要求所產(chǎn)生的散列碼盡量要分布均勻,以充分利用存儲(chǔ)數(shù)組的空間,但是即使分布再均勻,數(shù)組的容量都是有限的,如果數(shù)據(jù)的數(shù)量超過數(shù)組容量的時(shí)候,就不可避免地要面臨兩個(gè)key值有相同散列碼而共享一個(gè)數(shù)組的下標(biāo),這就是所謂的散列沖突。
為了解決散列沖突,Java在實(shí)現(xiàn)HashMap時(shí)用的是外部鏈接的方法:數(shù)組中保存的并不是Value值,而是一個(gè)鏈?zhǔn)降膶ο?,這個(gè)鏈?zhǔn)綄ο笾芯€性保存著所有散列碼為當(dāng)前數(shù)組下標(biāo)key的鍵值對。
當(dāng)進(jìn)行查詢操作時(shí),先通過散列碼定位到對應(yīng)的鏈表中,然后在鏈表中線性查找滿足條件的元素,而不是對于所有的數(shù)據(jù)進(jìn)行線性查找,這邊便是HashMap查找效率高的原因。如果存儲(chǔ)數(shù)組的大小和散列函數(shù)設(shè)計(jì)得當(dāng),發(fā)生散列沖突的次數(shù)越少,每個(gè)鏈表中的數(shù)據(jù)越少,HashMap的效率就越高。
以下是《Thinking in Java》中給出的HashMap簡單的實(shí)現(xiàn),以便大家了解散列碼的工作原理,其中鏈表是用list實(shí)現(xiàn)的:
public class SimpleHashMap<K,V> extends AbstractMap<K,V> {
// Choose a prime number for the hash table
// size, to achieve a uniform distribution:
static final int SIZE = 997;
// You can't have a physical array of generics,
// but you can upcast to one:
@SuppressWarnings("unchecked")
LinkedList<MapEntry<K,V>>[] buckets =
new LinkedList[SIZE];
public V put(K key, V value) {
V oldValue = null;
int index = Math.abs(key.hashCode()) % SIZE;
if(buckets[index] == null)
buckets[index] = new LinkedList<MapEntry<K,V>>();
LinkedList<MapEntry<K,V>> bucket = buckets[index];
MapEntry<K,V> pair = new MapEntry<K,V>(key, value);
boolean found = false;
ListIterator<MapEntry<K,V>> it = bucket.listIterator();
while(it.hasNext()) {
MapEntry<K,V> iPair = it.next();
if(iPair.getKey().equals(key)) {
oldValue = iPair.getValue();
it.set(pair); // Replace old with new
found = true;
break;
}
}
if(!found)
buckets[index].add(pair);
return oldValue;
}
public V get(Object key) {
int index = Math.abs(key.hashCode()) % SIZE;
if(buckets[index] == null) return null;
for(MapEntry<K,V> iPair : buckets[index])
if(iPair.getKey().equals(key))
return iPair.getValue();
return null;
}
public Set<Map.Entry<K,V>> entrySet() {
Set<Map.Entry<K,V>> set= new HashSet<Map.Entry<K,V>>();
for(LinkedList<MapEntry<K,V>> bucket : buckets) {
if(bucket == null) continue;
for(MapEntry<K,V> mpair : bucket)
set.add(mpair);
}
return set;
}
}
該代碼需要有一下幾點(diǎn)說明:
- 以散列碼為下標(biāo)的數(shù)組被稱為散列表,散列表的中位置被稱為桶位(bucket),桶排序也和桶位有關(guān),故此得名;
- 原來認(rèn)為,理論上散列表的大小最好為質(zhì)數(shù)(原因來自于模素?cái)?shù)的限域 mod P,這是一種完備的等價(jià)劃分,其結(jié)果會(huì)分布均勻),但是現(xiàn)在經(jīng)過大量的測試發(fā)現(xiàn),散列表取2的整數(shù)次方的效果更好,因?yàn)镠ashMap中get方法使用的頻率最高,而get方法中涉及到對于散列表大小的除法和取余數(shù),雖然一般數(shù)字對于這些操作很慢,但是2的整數(shù)次冪可以使用掩碼(mask)代替除法提高效率,低效除法對于性能的影響。
3 如何覆蓋hashCode()方法
在實(shí)現(xiàn)hashCode()的時(shí)候,有以下幾點(diǎn)設(shè)計(jì)原則需要注意:
- 同一個(gè)對象無論何時(shí)調(diào)用hashCode方法都應(yīng)該生成同樣的散列碼,因此不能依賴對象中易變數(shù)據(jù)生成散列碼。
- hashCode方法也盡量不能完全依賴具有唯一性的信息,比如默認(rèn)this值,默認(rèn)hashCode方法就是返回對象存儲(chǔ)地址,這樣做雖然保證了每個(gè)對象都是不同的散列碼,但是該散列碼沒有意義,兩個(gè)邏輯上相同的對象(比如內(nèi)容相同String類對象)也會(huì)生成不同的散列碼,所以生成散列碼需要依賴對象的有意義的信息;
- hashCode方法和equal方法等價(jià),也就是說調(diào)用equal方法相等的兩個(gè)對象,其散列值也應(yīng)該是相同的,反之也成立。
- hashCode方法運(yùn)算過程不能太復(fù)雜,因?yàn)樯⒘写a是為了追求速度而設(shè)計(jì)的,所有不能在生成散列碼的過程中過度浪費(fèi)時(shí)間;
- 散列碼應(yīng)該盡量均勻分布,以減少在線性查詢過程的平均時(shí)間;
《Effective Java》給出了一種實(shí)現(xiàn)hashCode的指導(dǎo)方法:
- 對于int變量result = 某個(gè)非0的變量,比如17;
- 為對象內(nèi)每個(gè)有意義的域f(也就是在執(zhí)行equal方法時(shí)需要對比的域),計(jì)算出一個(gè)int散列碼c:
域類型 | 計(jì)算 |
---|---|
boolean | c = f ? 0 : 1 |
byte、 char、short、int | c = (int)f |
long | c = (int)(f^(f>>32)) |
float | c = Float.floatToIntBits(f) |
double | 將其轉(zhuǎn)化為long型,再計(jì)算 |
Object對象 | c = f.hashCode() |
數(shù)組 | 對于每個(gè)元素都應(yīng)用以上規(guī)則 |
- 依次迭代計(jì)算散列碼:
result = 37* result + c ; - 返回result;
- 確定相等的實(shí)例具有相同散列碼,反之也要成立。
下面是《Thinking in Java》中給出的依照上面的類實(shí)現(xiàn)的CounterString,其散列碼是依據(jù)String類內(nèi)容和id生成的:
public class CountedString {
private static List<String> created =
new ArrayList<String>();
private String s;
private int id = 0;
public CountedString(String str) {
s = str;
created.add(s);
// id is the total number of instances
// of this string in use by CountedString:
for(String s2 : created)
if(s2.equals(s))
id++;
}
public String toString() {
return "String: " + s + " id: " + id +
" hashCode(): " + hashCode();
}
public int hashCode() {
// The very simple approach:
// return s.hashCode() * id;
// Using Joshua Bloch's recipe:
int result = 17;
result = 37 * result + s.hashCode();
result = 37 * result + id;
return result;
}
public boolean equals(Object o) {
return o instanceof CountedString &&
s.equals(((CountedString)o).s) &&
id == ((CountedString)o).id;
}
}
4 HashMap源碼分析
說了這么多,相信大家對于散列和散列碼已經(jīng)有了一定的了解,基于散列碼的角度,讓我們再來看看真實(shí)情況下HashMap的源碼(Java 1.7)
4.1 HashMap基礎(chǔ)
首先,為了效率考慮,HashMap中散列表為Entry類型的數(shù)組:
/**
* The default initial capacity - MUST be a power of two.
*/
static final int DEFAULT_INITIAL_CAPACITY = 16;
/**
* The table, resized as necessary. Length MUST Always be a power of two.
*/
transient Entry<K,V>[] table;
散列表大小默認(rèn)為16,在需要的情況下,散列表的大小可以重置,就像ArrayList那樣,但是大小必須是2的整數(shù)冪。
那什么時(shí)候散列表的大小要重置? HashMap為散列表設(shè)置了loadFactor負(fù)載因子這個(gè)屬性,當(dāng)散列表中的Entry數(shù)量達(dá)到閾值時(shí)(threshold = capacity * load factor),散列表的大小就會(huì)擴(kuò)展為原來的2倍。
/**
* The next size value at which to resize (capacity * load factor).
* @serial
*/
int threshold;
/**
* The load factor for the hash table.
*
* @serial
*/
final float loadFactor;
/**
* The load factor used when none specified in constructor.
*/
static final float DEFAULT_LOAD_FACTOR = 0.75f;
散列表中的元素Entry是HashMap類中的靜態(tài)內(nèi)部類,為Map.Entry<K,V>接口的實(shí)現(xiàn),表示一個(gè)鍵值對條目:
static class Entry<K,V> implements Map.Entry<K,V> {
final K key;
V value;
Entry<K,V> next;
int hash;
/**
* Creates new entry.
*/
Entry(int h, K k, V v, Entry<K,V> n) {
value = v;
next = n;
key = k;
hash = h;
}
.......
}
注意Entry中包含域Entry<K,V> next,說明這一種鏈?zhǔn)浇Y(jié)構(gòu),以此實(shí)現(xiàn)上一節(jié)提到的外部鏈接來解決散列碰撞。
4.2 put方法
下面看一下如何向散列表中添加鍵值對:
public V put(K key, V value) {
//1. 如果鍵為null,則進(jìn)入key為null的流程
if (key == null)
return putForNullKey(value);
//2. 獲取key的散列值,二次散列
int hash = hash(key);
//3. 根據(jù)散列碼確定在散列表中的位置
int i = indexFor(hash, table.length);
//4. 如果能在散列表中找到對應(yīng)的鍵值對,則更新
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;
}
}
//5. 沒能找到鍵值對,則創(chuàng)建加入該鍵值對
modCount++;
addEntry(hash, key, value, i);
return null;
}
根據(jù)注解中標(biāo)識(shí)依次進(jìn)行解釋:
- 由于HashMap允許key為空,所以當(dāng)發(fā)現(xiàn)key==null時(shí),調(diào)用方法putForNullKey:
private V putForNullKey(V value) {
for (Entry<K,V> 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++;
addEntry(0, null, value, 0);
return null;
}
該方法內(nèi)容和put方法類似,只不過把key改為null,插入位置默認(rèn)為0位,這里便不再展開討論。
- 當(dāng)確定key不為空后,就開始計(jì)算key的散列碼:
//2. 獲取key的散列值,二次散列
int hash = hash(key);
這里是HashMap一次經(jīng)典代碼,其中使用了二次散列:
final int hash(Object k) {
//散列碼初始值
int h = 0;
//1. 是否啟動(dòng)改進(jìn)散列值模式;
if (useAltHashing) {
if (k instanceof String) {
return sun.misc.Hashing.stringHash32((String) k);
}
h = hashSeed;
}
//2. 獲得第一次散列碼;
h ^= k.hashCode();
//3. 防止因散列表大小為2的冪次而造成的散列碰撞;
h ^= (h >>> 20) ^ (h >>> 12);
return h ^ (h >>> 7) ^ (h >>> 4);
}
- 因?yàn)镾un公司提供了增強(qiáng)的計(jì)算散列碼的方法,如果當(dāng)前配置環(huán)境支持這種選擇,就可以啟動(dòng)增強(qiáng)模式。該模式下,String類型的散列碼已經(jīng)直接可以得到;而對于其他類型,也挺通過了一個(gè)散列種子hashSeed來幫助減少散列碰撞的發(fā)生。
- 第一次散列,是通過Key本身的散列函數(shù)完成;
- 第二次散列是為了減少因散列表大小為2的冪次而造成的散列碰撞。
當(dāng)散列表大小capacity是2的指數(shù),如果兩個(gè)對象的hashCode值的低位相同,很有可能導(dǎo)致hashCode/capacity的值相同,就會(huì)出現(xiàn)沖突。
0101 0000 0000 1111 = 20495
0111 0000 0000 1111 = 28687
假如hashmap的capacity是16,那么20495%16 = 15,28687%16=15,散列碼沖突。
注釋3處的位移操作就是讓高位的數(shù)值也參與到散列值的計(jì)算中,具體分析請見http://www.iteye.com/topic/709945二次散列的位移
- 獲得散列碼之后,使用散列碼確定該值其在散列表中的位置:
/**
* Returns index for hash code h.
*/
static int indexFor(int h, int length) {
return h & (length-1);
}
上文已經(jīng)提過,對于2的冪次的取余數(shù)可以通過位與(&)掩碼來實(shí)現(xiàn),length-1便是length的掩碼,這一步實(shí)際上就是高效地實(shí)現(xiàn)了取余。
- 確定元素在散列表中位置后,就開始查找外部鏈表中是否包含該key,請注意key是否存在的條件
e.hash == hash && ((k = e.key) == key || key.equals(k))
這里不光使用了散列碼,還調(diào)用了equal方法,所以要使用HashMap的類必須要同時(shí)正確覆蓋hashCode和equal兩個(gè)方法。
- 如果沒有找到該Key,就會(huì)添加一個(gè)鍵值對條目。在添加新條目之前,會(huì)執(zhí)行modCount++。modCount的定義如下:
/**
* The number of times this HashMap has been structurally modified
* Structural modifications are those that change the number of mappings in
* the HashMap or otherwise modify its internal structure (e.g.,
* rehash). This field is used to make iterators on Collection-views of
* the HashMap fail-fast. (See ConcurrentModificationException).
*/
transient int modCount;
由于HashMap不是線程安全的,以犧牲進(jìn)程同步的開銷,來換取效率。退而求其次,HashMap使用了快速失敗(Fail-Fast)機(jī)制(也就是發(fā)現(xiàn)多線程數(shù)據(jù)不同步,就拋出異常)來處理這個(gè)問題。
例如使用HashMap的Iterator:開始時(shí)會(huì)將modCount的賦值給expectedModCount;在迭代過程中,通過每次比較兩者是否相等來判斷HashMap是否在內(nèi)部或被其它線程修改,如果modCount和expectedModCount值不一樣,證明有其他線程在修改HashMap的結(jié)構(gòu),會(huì)拋出異常。
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
所以HashMap的put、remove等操作都有modCount++的計(jì)算,以確保沒有多線程數(shù)據(jù)不同的問題。
更新modCount數(shù)值之后,開始正式添加鍵值對:
void addEntry(int hash, K key, V value, int bucketIndex) {
// 如果散列表的數(shù)量已經(jīng)閾值就開始擴(kuò)容散列表
if ((size >= threshold) && (null != table[bucketIndex])) {
//擴(kuò)容2倍
resize(2 * table.length);
hash = (null != key) ? hash(key) : 0;
bucketIndex = indexFor(hash, table.length);
}
//創(chuàng)建新條目
createEntry(hash, key, value, bucketIndex);
}
void createEntry(int hash, K key, V value, int bucketIndex) {
Entry<K,V> e = table[bucketIndex];
//新條目成為該桶位的第一個(gè)節(jié)點(diǎn),原有鏈表被放在其后面;
table[bucketIndex] = new Entry<>(hash, key, value, e);
size++;
}
4.3 containsKey方法
判斷是否含有key,也是HashMap一個(gè)常用的功能:
public boolean containsKey(Object key) {
return getEntry(key) != null;
}
final Entry<K,V> getEntry(Object key) {
int hash = (key == null) ? 0 : hash(key);
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;
}
有了put方法的知識(shí)的基礎(chǔ),以上代碼并不難理解,還是先利用兩次散列獲得散列碼,利用散列碼快速定位帶散列表上的桶位,在桶位處的鏈表上線性查找是否含有key,其判斷條件要求hashCode和equal方法都相等。
9.4.4 get方法
get操作時(shí)HashMap中使用頻率最高的,其實(shí)現(xiàn)和containsKey方法一樣都是基于getEntry方法:
public V get(Object key) {
//1. 如果key為空,則嘗試獲取NullKey位置的條目
if (key == null)
return getForNullKey();
//2. 根據(jù)key獲得條目
Entry<K,V> entry = getEntry(key);
//3. 返回條目;
return null == entry ? null : entry.getValue();
}
private V getForNullKey() {
//空key的桶位默認(rèn)為0
for (Entry<K,V> e = table[0]; e != null; e = e.next) {
if (e.key == null)
return e.value;
}
return null;
}
需要注意的是,由于put時(shí)NullKey對應(yīng)的桶位為0,所以在取出NullKey對應(yīng)的Value時(shí)也只直接去0位查找。
關(guān)于散列碼和HashMap的內(nèi)容暫時(shí)為大家介紹這些,當(dāng)然HashMap實(shí)現(xiàn)的內(nèi)容遠(yuǎn)比介紹的內(nèi)容要多,這里只是講解了和散列碼最為密切相關(guān)的部分,歡迎大家留言討論指正。