Geo*_*ton 1 java operator-precedence operator-keyword
这来自Java Generics和Collections中的Sets部分.下面的示例用于说明如何计算String的哈希码:
int hash = 0;
String str = "The red fox jumped over the fence";
/** calculate String Hashcode **/
for ( char ch: str.toCharArray()){
// hash *= 31 + ch; this evaluates to 0 ????
hash = hash * 31 + ch;
}
p("hash for " + str + " is " + hash);
Run Code Online (Sandbox Code Playgroud)
哈利为"红狐狸跳过篱笆"是1153233987386247098.这似乎是正确的.但是,如果我使用简写符号,*=,我的答案为0.
int hash = 0;
String str = "The red fox jumped over the fence";
/** calculate String Hashcode **/
for ( char ch: str.toCharArray()){
hash *= 31 + ch;
// hash = hash * 31 + ch;
}
p("hash for " + str + " is " + hash);
Run Code Online (Sandbox Code Playgroud)
"红狐狸跳过篱笆"的哈希是0
所以我很好奇如何使用*=运算符评估运算符优先级?
hash *= 31 + ch;
Run Code Online (Sandbox Code Playgroud)
是相同的
hash = hash * (31 + ch);
Run Code Online (Sandbox Code Playgroud)
这解释了0结果,因为它hash被初始化为0并且在每次乘法后保持为0.
在*=评估运算符之前,将评估其两个操作数(hash和31+ch).只有这样它们才会相乘,结果存储在hash变量中.
为了获得相同的输出
hash = hash * 31 + ch;
Run Code Online (Sandbox Code Playgroud)
使用*=,你将不得不打破操作:
hash *= 31;
hash += ch;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
79 次 |
| 最近记录: |