2014-12-06 16 views
0

當我看到Android的對的hashCode「舊」版本的任何參考源,它的實施是繼在有沒有在Android對的的hashCode實現,它使用XOR運算

喬希布洛赫的Effective Java的文本 - Best implementation for hashCode method

"Old" Pair.java

/** 
* Compute a hash code using the hash codes of the underlying objects 
* @return a hashcode of the Pair 
*/ 
public int hashCode() { 
    int result = 17; 
    result = 31 * result + first.hashCode(); 
    result = 31 * result + second.hashCode(); 
    return result; 
} 

然而,當我看到Android的對的hashCode 「最新」 版本,它看起來像這樣

"New" Pair.java

/** 
* Compute a hash code using the hash codes of the underlying objects 
* 
* @return a hashcode of the Pair 
*/ 
@Override 
public int hashCode() { 
    return (first == null ? 0 : first.hashCode())^(second == null ? 0 : second.hashCode()); 
} 

我想知道,有沒有什麼參考源,爲什麼正在使用XOR操作?我認爲我們不應該違反Josh Bloch的教導:)?

回答

0

目前尚不清楚爲什麼作者從素數技術轉移到XOR技術,但這種變化是由於需要支持Pair類中的null值。看到這個提交:https://github.com/android/platform_frameworks_base/commit/162fabbcf81157fddab1c38de09bdabaff8c068a#diff-e73c0c4c169861c96264276ecce62169。理論上,如果兩個對象都不是null,但是如果其中任何一個都是,則實現可以使用舊版本,那麼hashCode將變爲該對的非空分量的那個(或者如果兩者都爲空,則爲0)。

相關問題