淺談Java中的hashcode方法

  哈希表這個(gè)數(shù)據(jù)結(jié)構(gòu)想必大多數(shù)人都不陌生,而且在很多地方都會(huì)利用到hash表來提高查找效率。在Java的Object類中有一個(gè)方法:

public native int hashCode();

  根據(jù)這個(gè)方法的聲明可知,該方法返回一個(gè)int類型的數(shù)值,并且是本地方法,因此在Object類中并沒有給出具體的實(shí)現(xiàn)。

  為何Object類需要這樣一個(gè)方法?它有什么作用呢?今天我們就來具體探討一下hashCode方法。

一.hashCode方法的作用

  對(duì)于包含容器類型的程序設(shè)計(jì)語言來說,基本上都會(huì)涉及到hashCode。在Java中也一樣,hashCode方法的主要作用是為了配合基于散列的集合一起正常運(yùn)行,這樣的散列集合包括HashSet、HashMap以及HashTable。

  為什么這么說呢?考慮一種情況,當(dāng)向集合中插入對(duì)象時(shí),如何判別在集合中是否已經(jīng)存在該對(duì)象了?(注意:集合中不允許重復(fù)的元素存在)

  也許大多數(shù)人都會(huì)想到調(diào)用equals方法來逐個(gè)進(jìn)行比較,這個(gè)方法確實(shí)可行。但是如果集合中已經(jīng)存在一萬條數(shù)據(jù)或者更多的數(shù)據(jù),如果采用equals方法去逐一比較,效率必然是一個(gè)問題。此時(shí)hashCode方法的作用就體現(xiàn)出來了,當(dāng)集合要添加新的對(duì)象時(shí),先調(diào)用這個(gè)對(duì)象的hashCode方法,得到對(duì)應(yīng)的hashcode值,實(shí)際上在HashMap的具體實(shí)現(xiàn)中會(huì)用一個(gè)table保存已經(jīng)存進(jìn)去的對(duì)象的hashcode值,如果table中沒有該hashcode值,它就可以直接存進(jìn)去,不用再進(jìn)行任何比較了;如果存在該hashcode值,

就調(diào)用它的equals方法與新元素進(jìn)行比較,相同的話就不存了,不相同就散列其它的地址,所以這里存在一個(gè)沖突解決的問題,這樣一來實(shí)際調(diào)用equals方法的次數(shù)就大大降低了,說通俗一點(diǎn):Java中的hashCode方法就是根據(jù)一定的規(guī)則將與對(duì)象相關(guān)的信息(比如對(duì)象的存儲(chǔ)地址,對(duì)象的字段等)映射成一個(gè)數(shù)值,這個(gè)數(shù)值稱作為散列值。下面這段代碼是java.util.HashMap的中put方法的具體實(shí)現(xiàn)

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 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;

????}

  put方法是用來向HashMap中添加新的元素,從put方法的具體實(shí)現(xiàn)可知,會(huì)先調(diào)用hashCode方法得到該元素的hashCode值,然后查看table中是否存在該hashCode值,如果存在則調(diào)用equals方法重新確定是否存在該元素,如果存在,則更新value值,否則將新的元素添加到HashMap中。從這里可以看出,hashCode方法的存在是為了減少equals方法的調(diào)用次數(shù),從而提高程序效率。

  如果對(duì)于hash表這個(gè)數(shù)據(jù)結(jié)構(gòu)的朋友不清楚,可以參考這幾篇博文;

http://www.cnblogs.com/jiewei915/archive/2010/08/09/1796042.html

http://www.cnblogs.com/dolphin0520/archive/2012/09/28/2700000.html

http://www.java3z.com/cwbwebhome/article/article8/83560.html?id=4649

  有些朋友誤以為默認(rèn)情況下,hashCode返回的就是對(duì)象的存儲(chǔ)地址,事實(shí)上這種看法是不全面的,確實(shí)有些JVM在實(shí)現(xiàn)時(shí)是直接返回對(duì)象的存儲(chǔ)地址,但是大多時(shí)候并不是這樣,只能說可能存儲(chǔ)地址有一定關(guān)聯(lián)。下面是HotSpot JVM中生成hash散列值的實(shí)現(xiàn)

static inline intptr_tget_next_hash(Thread * Self, oop obj) {

??intptr_tvalue = 0 ;

??if(hashCode == 0) {

?????// This form uses an unguarded global Park-Miller RNG,

?????// so it's possible for two threads to race and generate the same RNG.

?????// On MP system we'll have lots of RW access to a global, so the

?????// mechanism induces lots of coherency traffic.

?????value = os::random() ;

??} else

??if(hashCode == 1) {

?????// This variation has the property of being stable (idempotent)

?????// between STW operations.? This can be useful in some of the 1-0

?????// synchronization schemes.

?????intptr_taddrBits = intptr_t(obj) >> 3 ;

?????value = addrBits ^ (addrBits >> 5) ^ GVars.stwRandom ;

??} else

??if(hashCode == 2) {

?????value = 1 ;??????????? // for sensitivity testing

??} else

??if(hashCode == 3) {

?????value = ++GVars.hcSequence ;

??} else

??if(hashCode == 4) {

?????value = intptr_t(obj) ;

??} else{

?????// Marsaglia's xor-shift scheme with thread-specific state

?????// This is probably the best overall implementation -- we'll

?????// likely make this the default in future releases.

?????unsigned t = Self->_hashStateX ;

?????t ^= (t << 11) ;

?????Self->_hashStateX = Self->_hashStateY ;

?????Self->_hashStateY = Self->_hashStateZ ;

?????Self->_hashStateZ = Self->_hashStateW ;

?????unsigned v = Self->_hashStateW ;

?????v = (v ^ (v >> 19)) ^ (t ^ (t >> 8)) ;

?????Self->_hashStateW = v ;

?????value = v ;

??}

??value &= markOopDesc::hash_mask;

??if(value == 0) value = 0xBAD ;

??assert(value != markOopDesc::no_hash, "invariant") ;

??TEVENT (hashCode: GENERATE) ;

??return value;

}

  該實(shí)現(xiàn)位于hotspot/src/share/vm/runtime/synchronizer.cpp文件下。

因此有人會(huì)說,可以直接根據(jù)hashcode值判斷兩個(gè)對(duì)象是否相等嗎?肯定是不可以的,因?yàn)椴煌膶?duì)象可能會(huì)生成相同的hashcode值。雖然不能根據(jù)hashcode值判斷兩個(gè)對(duì)象是否相等,但是可以直接根據(jù)hashcode值判斷兩個(gè)對(duì)象不等,如果兩個(gè)對(duì)象的hashcode值不等,則必定是兩個(gè)不同的對(duì)象。如果要判斷兩個(gè)對(duì)象是否真正相等,必須通過equals方法。

  也就是說對(duì)于兩個(gè)對(duì)象,如果調(diào)用equals方法得到的結(jié)果為true,則兩個(gè)對(duì)象的hashcode值必定相等;

  如果equals方法得到的結(jié)果為false,則兩個(gè)對(duì)象的hashcode值不一定不同;

  如果兩個(gè)對(duì)象的hashcode值不等,則equals方法得到的結(jié)果必定為false;

  如果兩個(gè)對(duì)象的hashcode值相等,則equals方法得到的結(jié)果未知。

二.equals方法和hashCode方法

在有些情況下,程序設(shè)計(jì)者在設(shè)計(jì)一個(gè)類的時(shí)候?yàn)樾枰貙慹quals方法,比如String類,但是千萬要注意,在重寫equals方法的同時(shí),必須重寫hashCode方法。為什么這么說呢?

  下面看一個(gè)例子:

class People{

????private String name;

????private int age;

????publi cPeople(String name,int age) {

????????this.name = name;

????????this.age = age;

????}??

????public void setAge(int age){

????????this.age = age;

????}

????@Override

????public boolean equals(Object obj) {

????????// TODO Auto-generated method stub

????????return this.name.equals(((People)obj).name) && this.age== ((People)obj).age;

????}

}

public class Main {

????public static void main(String[] args) {

????????People p1 = newPeople("Jack", 12);

????????System.out.println(p1.hashCode());

????????HashMap hashMap = newHashMap();

????????hashMap.put(p1, 1);

????????System.out.println(hashMap.get(newPeople("Jack", 12)));

????}

}

  在這里我只重寫了equals方法,也就說如果兩個(gè)People對(duì)象,如果它的姓名和年齡相等,則認(rèn)為是同一個(gè)人。

這段代碼本來的意愿是想這段代碼輸出結(jié)果為“1”,但是事實(shí)上它輸出的是“null”。為什么呢?原因就在于重寫equals方法的同時(shí)忘記重寫hashCode方法。

  雖然通過重寫equals方法使得邏輯上姓名和年齡相同的兩個(gè)對(duì)象被判定為相等的對(duì)象(跟String類類似),但是要知道默認(rèn)情況下,hashCode方法是將對(duì)象的存儲(chǔ)地址進(jìn)行映射。那么上述代碼的輸出結(jié)果為“null”就不足為奇了。原因很簡(jiǎn)單,p1指向的對(duì)象和

  System.out.println(hashMap.get(new People("Jack", 12)));這句中的new People("Jack", 12)生成的是兩個(gè)對(duì)象,它們的存儲(chǔ)地址肯定不同。下面是HashMap的get方法的具體實(shí)現(xiàn):

public V get(Object key) {

????????if(key == null)

????????????return getForNullKey();

????????int hash = hash(key.hashCode());

????????for(Entry e = table[indexFor(hash, table.length)];

?????????????e != null;

?????????????e = e.next) {

????????????Object k;

????????????if(e.hash == hash && ((k = e.key) == key || key.equals(k)))

????????????????return e.value;

????????}

????????return null;

????}

  所以在hashmap進(jìn)行g(shù)et操作時(shí),因?yàn)榈玫降膆ashcdoe值不同(注意,上述代碼也許在某些情況下會(huì)得到相同的hashcode值,不過這種概率比較小,因?yàn)殡m然兩個(gè)對(duì)象的存儲(chǔ)地址不同也有可能得到相同的hashcode值),所以導(dǎo)致在get方法中for循環(huán)不會(huì)執(zhí)行,直接返回null。

因此如果想上述代碼輸出結(jié)果為“1”,很簡(jiǎn)單,只需要重寫hashCode方法,讓equals方法和hashCode方法始終在邏輯上保持一致性。

class People{

????private String name;

????private int age;

????public People(String name,int age) {

????????this.name = name;

????????this.age = age;

????}??

????public void setAge(int age){

????????this.age = age;

????}

????@Override

????public int hashCode() {

????????// TODO Auto-generated method stub

????????return name.hashCode()*37+age;

????}

????@Override

????public boolean equals(Object obj) {

????????// TODO Auto-generated method stub

????????return this.name.equals(((People)obj).name) && this.age== ((People)obj).age;

????}

}

public class Main {

????public static void main(String[] args) {

????????People p1 = new People("Jack", 12);

????????System.out.println(p1.hashCode());

????????HashMap hashMap = newHashMap();

????????hashMap.put(p1, 1);

????????System.out.println(hashMap.get(newPeople("Jack", 12)));

????}

}

  這樣一來的話,輸出結(jié)果就為“1”了。

  下面這段話摘自Effective Java一書:

在程序執(zhí)行期間,只要equals方法的比較操作用到的信息沒有被修改,那么對(duì)這同一個(gè)對(duì)象調(diào)用多次,hashCode方法必須始終如一地返回同一個(gè)整數(shù)。

如果兩個(gè)對(duì)象根據(jù)equals方法比較是相等的,那么調(diào)用兩個(gè)對(duì)象的hashCode方法必須返回相同的整數(shù)結(jié)果。

如果兩個(gè)對(duì)象根據(jù)equals方法比較是不等的,則hashCode方法不一定得返回不同的整數(shù)。

  對(duì)于第二條和第三條很好理解,但是第一條,很多時(shí)候就會(huì)忽略。在《Java編程思想》一書中的P495頁也有同第一條類似的一段話:

“設(shè)計(jì)hashCode()時(shí)最重要的因素就是:無論何時(shí),對(duì)同一個(gè)對(duì)象調(diào)用hashCode()都應(yīng)該產(chǎn)生同樣的值。如果在講一個(gè)對(duì)象用put()添加進(jìn)HashMap時(shí)產(chǎn)生一個(gè)hashCdoe值,而用get()取出時(shí)卻產(chǎn)生了另一個(gè)hashCode值,那么就無法獲取該對(duì)象了。所以如果你的hashCode方法依賴于對(duì)象中易變的數(shù)據(jù),用戶就要當(dāng)心了,因?yàn)榇藬?shù)據(jù)發(fā)生變化時(shí),hashCode()方法就會(huì)生成一個(gè)不同的散列碼”。

  下面舉個(gè)例子:

class People{

????private String name;

????private int age;

????public People(String name,int age) {

????????this.name = name;

????????this.age = age;

????}??

????public void setAge(int age){

????????this.age = age;

????}

????@Override

????public int hashCode() {

????????// TODO Auto-generated method stub

????????return name.hashCode()*37+age;

????}

????@Override

????public boolean equals(Object obj) {

????????// TODO Auto-generated method stub

????????return this.name.equals(((People)obj).name) && this.age== ((People)obj).age;

????}

}

public class Main {

????public static void main(String[] args) {

????????People p1 = newPeople("Jack", 12);

????????System.out.println(p1.hashCode());

????????HashMap hashMap = newHashMap();

????????hashMap.put(p1, 1);

????????p1.setAge(13);

????????System.out.println(hashMap.get(p1));

????}

}

  這段代碼輸出的結(jié)果為“null”,想必其中的原因大家應(yīng)該都清楚了。

  因此,在設(shè)計(jì)hashCode方法和equals方法的時(shí)候,如果對(duì)象中的數(shù)據(jù)易變,則最好在equals方法和hashCode方法中不要依賴于該字段。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容