我在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) 当我试图从具有一条记录的hashmap中获取错误时,我一直变为空.最后我用以下方式测试它:
Iterator<Position> it = pieces.keySet().iterator();
while (it.hasNext()){
System.out.println("object from key >> " + pieces.get(it.next()));
}
Iterator<Piece> itt = pieces.values().iterator();
while (itt.hasNext()){
System.out.println("direct object >> " + itt.next().getPosition());
}
Run Code Online (Sandbox Code Playgroud)
我得到的输出是:
object from key >> null
direct object >> application.Position@37
Run Code Online (Sandbox Code Playgroud)
我已经显示的代码被使用,因为它之间没有任何其他东西.
关于位置对象,我重写了hashCode()函数,以根据Position类的值返回hashCode.因此,当对象中的变量发生变化时,HashCode会发生变化.上面的代码在位置对象的值更改之前很有效.但是一旦我改变了,我就会通过密钥获得空值.