2013-10-12 46 views
1

我在HashMap.java中看到了下面的代碼。在Java中^ =是什麼意思?

h ^= k.hashCode(); 
    // 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); 

幾個隨機輸入產生類似於另外一個輸出端,但下面的代碼導致0

int p = 10; 
    p ^= 10; 
    System.out.println("_______ " + p); 
+0

考慮這個'char ch ='1'; ch^= Long.MIN_VALUE;';) –

回答

4

^=操作者確實在左側和操作數的變量的XOR,然後做一個賦值給結果的變量。

XOR與自己的東西,你得到零。這是將寄存器設置爲零的有效方法,因爲它不移動任何內存。

+0

+1有關效率的評論。 –

1

^稱爲XOR (Exclusive disjunction or exclusive or),邏輯運算符,它遵循:

1 xor 1 = 0 
1 xor 0 = 1 
0 xor 1 = 1 
0 xor 0 = 0 

作爲p^=10相當於:

p = p^10; or, p = p xor 10 

p = 10你的操作是簡單的:,(10^10),這將導致在0

1

^=是按位異或運算符。 x ^= 2x = x^2相同。

1

^是邏輯XOR(異或)的符號。

當放置在等號前面時,這意味着'與給定值異或,並將結果寫回自己'。 a^=值與說a = a ^值相同。

這可能使其更清晰,如果與其他運營商,如加做:

如:

int counter = 14; 

// Add 20 to counter (could also be written counter = counter + 20): 
counter += 20; 

// Counter is now 34 
1

它是Java中的compound assignment operator

x op= y相當於x = x op y(鬆散說,見上面的鏈接)。

例如:

x += y;相當於x = x + y;

x -= y;等同於x = x - y;

等等...


作爲參考,這是的complete list在java中所有這些運算符:

+= -= *= /= &= |= ^= %= <<= >>= >>>=

+0

也有隱式轉換。;) –

+0

@PeterLawrey雅,我不知道如何把它放在複雜的情況下:-) –

+0

我喜歡的例子是'char ch ='0'; ch * = 1.1;''和'ch'是'4' –