【发布时间】:2017-10-13 16:41:17
【问题描述】:
这来自 Java 泛型和集合中的集合部分。下面举例说明如何计算String的hashcode:
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);
“红狐跳过栅栏”的哈希值为 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);
“红狐跳过栅栏”的哈希值为 0
所以我很好奇如何使用 *= 评估运算符优先级 运营商?
【问题讨论】:
-
The precedence of
*=(and all other assignment operators) is the same as for=。这就是为什么它在乘法之前进行加法并且你得到零。
标签: java operator-keyword operator-precedence