2014-05-06 26 views
-2

這裏是從HashMap實現的方法,從java.util包:secondaryHash(對象鍵)實現的解釋

static int secondaryHash(Object key) { 
    int hash = key.hashCode(); 
    hash ^= (hash >>> 20)^(hash >>> 12); 
    hash ^= (hash >>> 7)^(hash >>> 4); 
    return hash; 
} 

有人能解釋這些是什麼^=>>>^事情,什麼是怎麼回事?

+1

閱讀[這裏](http://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html)。 – alex2410

+2

'^'是一個按位XOR,'>>>'是一個無符號的右移。 '^ ='與'+ ='具有相同的含義,但是具有按位異或。 –

+0

你探索了什麼實現? HotSpot的'HashMap'沒有'secondaryHash()'方法。 – leventov

回答

3

x ^= y:是x = x^y短手操作。

^:是二進制獨佔運算符XOR

y >>> x:是二進制移位操作者的Y -Bits向左填充而X -Bits向右移位其中的所有位。這意味着如果初始值是負數,標誌將不會被保留。

+0

+1。我今晚不會回答問題。 :P如果你的答案被接受,我會刪除我的。 – merlin2011

0

^運算符執行兩個整數量的bitwise XOR

^=+=類似,除了^

運營商>>>是一個邏輯右移,它向右移動每一位,刪除掉右邊的那些位。在左側0的填充在

static int secondaryHash(Object key) { 
    int hash = key.hashCode(); 
    hash ^= (hash >>> 20)^(hash >>> 12); // Set hash to equal to bitwise XOR of it with itself right shifted by 20 and right shifted by 12. 
    hash ^= (hash >>> 7)^(hash >>> 4); // Same thing for right shift by 7 and right shift by 4. 
    return hash; 
} 
+0

**^**不是OR,而是XOR! – Harmlezz

+0

@Harmlezz,修復。 – merlin2011