每Java文档中,哈希代码的String对象被计算为:
Run Code Online (Sandbox Code Playgroud)s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]使用
int算术,其中s[i]是 字符串的第i个字符,是字符串n的长度,并^指示取幂.
为什么31用作乘数?
我知道乘数应该是一个相对较大的素数.那么为什么不是29岁,37岁,甚至97岁?
我在HashSet比较中做了这个测试而equals 没有被调用
当farAway = false时,我想考虑等于(检查两个点距离的函数)
完全可编译的代码,你可以测试它,并告诉为什么在这个例子中没有调用equals.
public class TestClass{
static class Posicion
{
private int x;
private int y;
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Posicion other = (Posicion) obj;
if ( farAway(this.x, other.x, this.y, other.y,5)){
return false;
}
return true;
}
@Override
public int hashCode() {
int hash = 7; hash = 59 * hash + this.x; hash = 59 * …Run Code Online (Sandbox Code Playgroud)