首页 > 解决方案 > How to check if two objects are equal in java?

问题描述

Hi i'm new to java class and I am trying to compare two objects. In this case the circle consists of a point and a radius. I need to check both the point and radius if they are equal, but in my code the result is 'not equal' even though they are actually equal. sorry if my question is dumb. i've been trying to look for answers but still cant understand the problem :\

public class Circle{
private MyPoint point;
private float radius;
public Circle(){
    MyPoint temp = new MyPoint(0,0);
        point = temp;
        radius = 0;
    }

public Circle(MyPoint Center, float Radius){
    point = Center;
    radius = Radius;
}
public Circle(int x, int y, float Radius){
        MyPoint temp = new MyPoint(x,y);
        point = temp;
        radius = Radius;
}
public void setRadius(float Radius){
    radius = Radius;
}
public void setCenter(int x, int y){
        MyPoint temp = new MyPoint(x,y);
        point = temp;
}
public MyPoint getCenter(){
        return point;
}
public float getRadius(){
    return radius;
}
public boolean equals(Object obj){
            boolean ans = false;
            if(obj instanceof Circle){
                Circle circ = (Circle)obj;
                if(radius == (circ.radius) && point.equals( circ.point ) )
                    ans = true;
            }
            return ans;
}
public static void main(String args[]){
        Circle C1 = new Circle(10,20, 5);
        Circle C2 = new Circle(10,20, 5);
        if(C1.equals(C2))
            System.out.println("Equal");
        else
            System.out.println("Not Equal");

 }

Heres the inside of the MyPoint Class

public class MyPoint{
 private int x;
 private int y;
 public MyPoint(){}
 public MyPoint(int x, int y){
     this.x = x;
     this.y = y;
 }
 public String toString(){
     return "("+x+","+y+")";
 }
}

标签: javabooleanequals

解决方案


您的MyPoint课程没有 equals 方法,这意味着new MyPoint(1, 2)不等于new MyPoint(1, 2)(试试看!)。

而且,由于您的 Circle 的 equals 定义依赖于 MyPoint 的 equals 定义才能发挥作用 - 这会发生。

为了将来参考,您可以使用 lombok@Data@Value自动化这些东西 - 或者,您的 IDE 可以为您生成它(但这会留下丑陋的杂物,您必须记住在修改/添加/删除字段时进行更新),并且在 java15 中, Point 可能会成为一条记录,这也将消除为它显式编写等于代码的需要。


推荐阅读