方法调用何时等于

方法调用何时等于

本文介绍了HashSet'add'方法调用何时等于?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在HashSet比较中进行了此测试,等于 未被调用



我想在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;
}
返回true;
}

@Override
public int hashCode(){
int hash = 7; hash = 59 * hash + this.x; hash = 59 * hash + this.y;
返回哈希值;
}

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)));
}
}

编辑



- 有没有办法强制HashSet添加到调用equals?

解决方案

如果哈希码不同,则无需调用 equals(),因为它保证返回 false 。 / p>

这来自一般的 等于() hashCode()

现在你的班级打破了这份合同。你需要解决这个问题。


I did this test in a HashSet comparision and equals is not being called

I would like to consider equals when farAway=false(A function to check two point distances)

Full compilable code, you could test it, and tells why equals is not being called in this example.

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)));
    }
}

EDIT

-Is there a way to force HashSet add to call equals?

解决方案

If the hash codes differ, there is no need to call equals() since it is guaranteed to return false.

This follows from the general contract on equals() and hashCode():

Right now your class is breaking that contract. You need to fix that.

这篇关于HashSet'add'方法调用何时等于?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 17:17