gpt4 book ai didi

Point 类的 Java hashCode

转载 作者:搜寻专家 更新时间:2023-10-31 08:13:58 25 4
gpt4 key购买 nike

我有一个简单的自定义 Point 类,如下所示,我想知道我的 hashCode 实现是否可以改进,或者这是否是最好的实现。

public class Point 
{
private final int x, y;

public Point(int x, int y)
{
this.x = x;
this.y = y;
}

public int getX()
{
return x;
}

public int getY()
{
return y;
}

@Override
public boolean equals(Object other)
{
if (this == other)
return true;

if (!(other instanceof Point))
return false;

Point otherPoint = (Point) other;
return otherPoint.x == x && otherPoint.y == y;
}


@Override
public int hashCode()
{
return (Integer.toString(x) + "," + Integer.toString(y)).hashCode();
}

}

最佳答案

请不要使用字符串。这背后有很多理论和几种实现方式(除法、乘法等)。如果你有大约一个小时的时间,你可以观看这个 MIT-Class

话虽这么说,但这是 Netbeans 7.1 的建议:

@Override
public int hashCode() {
int hash = 7;
hash = 71 * hash + this.x;
hash = 71 * hash + this.y;
return hash;
}

2015 年 10 月编辑

我很久以前就开始使用 IntelliJ,现在我过得更快乐了。这就是它的自动 hashCode 生成产生的结果。它不那么冗长。还要注意质数的使用。

@Override
public int hashCode() {
int result = x;
result = 31 * result + y;
return result;
}

关于Point 类的 Java hashCode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9135759/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com