我在HashSet比较中做了这个测试,equals
没有被调用
我想在遥远=假时考虑等于(检查两点距离的功能)
完全可编译的代码,您可以对其进行测试,并说明为什么在此示例中未调用 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 * hash + this.y;
return hash;
}
Posicion(int x0, int y0) {
x=x0;
y=y0;
}
private boolean farAway(int x, int x0, int y, int y0, int i) {
return false;
}
}
public static void main(String[] args) {
HashSet<Posicion> test=new HashSet<>();
System.out.println("result:"+test.add(new Posicion(1,1)));
System.out.println("result:"+test.add(new Posicion(1,2)));
}
}
编辑
-有没有办法强制哈希集添加调用等于?
如果哈希码不同,则无需调用equals()
,因为它保证返回false
。
这源于equals()
和hashCode()
的总合同:
如果根据
equals(Object)
方法两个对象相等,则对两个对象中的每一个调用hashCode
方法必须产生相同的整数结果。
现在你的班级正在打破这个合同。你需要解决这个问题。
如果您希望始终调用equals()
,只需始终返回,例如hashCode()
中的0
。这样,所有项目都具有相同的哈希代码,并且纯粹与equals()
进行比较。
public int hashCode() {
return 0;
}
听起来HashSet不适合你。听起来您想要一种比较两个位置的自定义方法。而不是说"两个位置完全相等吗?相反,您应该考虑使用带有比较器的TreeSet。这样,您可以编写一个"IsWithinRangeComparator"并在那里进行范围检查。
如上所述,当对象相等时,它们的哈希码也应该相同。您可以像下面这样对哈希码计算进行简单的修复。
public int hashCode() {
int hash = 7; hash = 59 * hash + this.x; hash = 59 * hash + this.y;
boolean faraway=farAway(this.x, other.x, this.y, other.y,5);
hash=59*hash+(faraway?1:0); //include faraway also as part of hashcode computation
return hash;
}