简体   繁体   English

如果类具有引用类型成员java,如何实现equality和hashCode方法?

[英]how do you implement the equality and hashCode method if the class has reference type members java?

I am trying to implement the following example to override the equality and hashCode method if the class has reference type member but no luck. 我正在尝试实现以下示例,以在类具有引用类型成员但没有运气的情况下覆盖均等和hashCode方法。 Any help would be highly appreciated. 任何帮助将不胜感激。 Thanking you all in advance.. 谢谢大家..

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

} 


class Circle 
{
    int radius; 
    Point point ;

    Circle(int x, int y, int radius)
    {
        point = new Point (x ,y);
        this.radius = radius;
    }



    @Override
    public boolean equals(Object arg) {

        if(arg == null) return false;
        if(arg == this) return true;
        if(arg instanceof Circle) 
        {
            if(this.point ==((Circle) arg).point && this.radius == ((Circle)           arg).radius)
            {
                return true;
            }

        } 


        return false;
    }

    @Override
    public int hashCode() {

        return point.hashCode() ^ this.radius;
    }

}


public class TestClass{

    public static void main(String args[])
    {
        Set<Circle> circle = new HashSet<> ();
        circle.add(new Circle(10,20,40));

        System.out.println(circle.contains(new Circle(10,20,40))); //
    }

}

**************************Edited Version, suggested by Alnitak***************** **************************编辑版本,由Alnitak建议*****************

Now i do get the expected result "true" for equal and "false" for non-equal objects. 现在,对于相等的对象,我确实获得了预期的结果“ true”,对于非相等的对象则获得了“ false”。 But the print statement in the Circle's equal method is not executed when the objects values are not equal. 但是,当对象值不相等时,不会执行Circle的equal方法中的print语句。 I don't know what i am missing, though i get the equality result "false" as expected for non equal objects. 我不知道我缺少什么,尽管我得到了对非相等对象所期望的相等结果“ false”。

 class Point{
    private int x, y;
    Point (int x, int y)
    {
        this.x =x;
        this.y = y;
    }
    @Override
    public boolean equals(Object arg) {
        if(arg == null ) return false;
        if(arg== this) return true;
        if(arg instanceof Point)
        {
            Point p = (Point) arg;
            if(p.x == x && p.y == y )
            {
                return true;
            }
        }
        return false;

    }
    @Override
    public int hashCode() {

        return (this.x*1124739) ^ (this.y*95);
    }

} 


class Circle 
{
    int radius; 
    Point point ;

    Circle(int x, int y, int radius)
    {

        System.out.println("Circle object created x= " + x);
        point = new Point (x ,y);
        this.radius = radius;
    }



    @Override
    public boolean equals(Object arg) {

        if(arg == null) return false;
        if(arg == this) return true;
        if(arg instanceof Circle)   
        {
            System.out.println("checking circles objects for equality "); 
            // Doesn't get printed when circle objects values are not equal

            Circle c = (Circle) arg;
            return (point.equals(c.point) && radius == c.radius);

        } 


        return false;
    }

    @Override
    public int hashCode() {

        return point.hashCode() ^ this.radius *37;
    }

}


public class TestClass{

    public static void main(String args[])
    {
        Set<Circle> circle = new HashSet<> ();
        circle.add(new Circle(10,20,40));

        System.out.println(circle.contains(new Circle(11,20,40))); //
    }

}

Your existing Circle.equals() method only checks for referential equality, not value equality. 您现有的Circle.equals()方法仅检查引用相等,而不检查值相等。 It will always fail because each Circle contains a newly constructed Point object that is unique to that instance. 它将始终失败,因为每个Circle包含一个新构造的Point对象,该对象对该实例是唯一的。

You should create a proper hashCode and equals method for the Point class. 您应该为Point类创建一个正确的hashCodeequals方法。

Within the Circle class you can then use Point.equals() to check for value equality of the held reference, for example: 然后,您可以在Circle类中使用Point.equals()来检查所保存引用的值是否相等,例如:

public boolean equals(Object arg) {
    if (arg == null) return false; 
    if (arg == this) return true;
    if (arg instanceof Circle) {
        Circle c = (Circle)arg;
        return radius == c.radius && point.equals(c.point);
    }
    return false;
}

For the Circle hashcode, a simple option is to generate a local hashcode and xor it with the Point's hashcode. 对于Circle哈希码,一个简单的选项是生成本地哈希码,并将其与Point的哈希码进行xor

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Java hashCode()方法是衡量对象相等性的可靠方法吗? - Is Java hashCode() method a reliable measure of object equality? 如何在Intellij中对其成员进行排序的方式生成Java的哈希码方法? - How to generate java's hashcode method in intellij with its members sorted? 您如何传递对“类”类型的引用? - How do you pass a reference to type 'class'? 当toString()和hashCode()被覆盖时,如何获取java中对象的“对象引用”? - How do you get the “object reference” of an object in java when toString() and hashCode() have been overridden? JAVA:如何访问单独类中的数据成员? - JAVA: How do you access data members in a separate class? 如何实现hashCode和equals方法 - How to implement hashCode and equals method 如何在Java 1.6中实现Objects.hashcode - How do I implement Objects.hashcode within java 1.6 在哪些情况下,Java 引用相等性可能与尚未覆盖 equals() 类型的对象的 equals() 相等性不同? - In which circumstances Java reference equality could be different to equals() equality for an object of a type which has not overridden equals()? 如何使用equals()和hashCode()实现近似几何相等 - How to implement approximate geometric equality using equals() and hashCode() 为具有浮点成员的类实现“容忍”`equals`和`hashCode` - Implement “tolerant” `equals` & `hashCode` for a class with floating point members
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM