java - 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+")";
}
}
解决方案
您的MyPoint
课程没有 equals 方法,这意味着new MyPoint(1, 2)
不等于new MyPoint(1, 2)
(试试看!)。
而且,由于您的 Circle 的 equals 定义依赖于 MyPoint 的 equals 定义才能发挥作用 - 这会发生。
为了将来参考,您可以使用 lombok@Data
或@Value
自动化这些东西 - 或者,您的 IDE 可以为您生成它(但这会留下丑陋的杂物,您必须记住在修改/添加/删除字段时进行更新),并且在 java15 中, Point 可能会成为一条记录,这也将消除为它显式编写等于代码的需要。
推荐阅读
- node.js - 使用 NoSQL 数据库计算用户数
- r - R中的列表可以很大吗?R 不会让我创建这个列表
- c# - 如何确定在 C# ASP.NET CORE MVC 5.0 中选择了哪个单选按钮
- python - 当给定一个类的相同实例的列表时,deepcopy 的行为如何
- python - 数据框中列值之间的成对交集操作
- mysql - MySQL Query 与另一个表的状态检查
- spring-boot - Spring JPA 投影 - 在嵌套对象列表中选择特定列
- python - 如何在每个循环获取新输出的 for 循环中附加一个数组?
- java - 如何使用 iText 5 将 PDF 文件嵌入到现有文件中
- mediawiki - MediaWiki 不同名称空间的不同站点标题