Her*_*che 9 java comparison equals hashset
我在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 * 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)));
}
}
Run Code Online (Sandbox Code Playgroud)
编辑
- 有没有办法强制HashSet添加到调用equals?
NPE*_*NPE 26
如果哈希码不同,则无需调用,equals()因为它保证返回false.
在此之前,从一般的合同上equals()和hashCode():
如果根据
equals(Object)方法两个对象相等,则hashCode在两个对象中的每一个上调用方法必须产生相同的整数结果.
现在你的班级打破了这份合同.你需要解决这个问题.
如果您想equals()将总是叫,只是总是返回,也就是说,0在hashCode().这样,所有项目都具有相同的哈希码,并且仅与之进行比较equals().
public int hashCode() {
return 0;
}
Run Code Online (Sandbox Code Playgroud)