![](/img/trans.png)
[英]Implementing equals and hashCode for objects with circular references in Java
[英]Implementing Equals and hashCode for my objects in Java
因此,我知道对此进行了广泛的讨论和讨论,而我只是想让我的平等工作适用于Shapes。 我创建了一个Shape类,它说明了什么类型的Shape(即矩形,三角形,圆形),并且如果它们具有相同的形状,我将尝试返回true。
主要用于测试...
Rectangle myRect = new Rectangle(3,5);
Rectangle myRect2 = new Rectangle(3,5);
if (myRect==myRect2){
System.out.println("Both the objects are equal");
}
else {
System.out.println("Both the objects are not equal");
}
和我实际的Shape类,带有覆盖的equals和hashcode。
abstract class Shape
{
abstract double area();
public Shape getShape(){
return shape;
}
@Override
public boolean equals(Object other) {
if (other == this) return true;
if (other == null) return false;
if (getClass() != other.getClass()) return false;
Shape shape = (Shape)other;
return(other==this);
}
@Override
public int hashCode() {
return shape.hashCode();
}
基本上,我的输出总是虚假,任何见解都会有所帮助,谢谢!
myRect==myRect2
仅当它们是相同的对象myRect==myRect2
返回true
。 您应该使用myRect.equals(myRect2);
在Java中,当涉及对象时,使用==
表示检查对象的地址值。 让我用一个例子解释一下:
Rectangle objA = new Rectangle(3,5);
Rectangle objB = objA;
此处, objA
在内存位置A上创建,而objB
指向内存位置A或objA
创建位置。 这意味着两个内存位置相同,这意味着objA == objB
将返回true。
但是在另一种情况下:
Rectangle objC = new Rectangle(3,5);
Rectangle objD = new Rectangle(3,5);
您可能会说,哦,它们的宽度和高度都相同,所以它们必须是相同的对象。 但是请注意,事实并非如此,因为objC
是在内存位置C上创建的,而objD
是在内存位置D上创建的,因为它们每个都是通过单独的new
(构造函数)调用创建的。 在这种情况下,内存位置是不同的,这意味着objC == objD
将返回false。
内存位置并不是这样命名的,我只是用它来更容易地描述我的示例。
当您想使用.equals
方法时,您正在考虑正确,这就是java用来比较两个对象的深度,而不仅仅是它们的地址。 但是在自定义类中,由用户定义何时两个对象相等以及何时不相等时该方法的工作方式。
但是您的.equals
实现有点错误。
这行检查对象other
是否指向this
存储位置。
if (other == this) return true;
但是稍后,您有以下两行:
Shape shape = (Shape)other;
return(other==this);
您无需对shape对象执行任何操作,因此,为什么还要创建它,也只是为垃圾收集器增加了工作量。 并且return other==this
有点多余,因为如果前面的行返回true,则这里唯一的可能是返回false,因此此检查只是return false
更复杂的版本。
当您使用稍后由其他派生类扩展的抽象类时,应在每个这些类中实现.equals
方法。 以您的案例为例,您可能想要比较两个矩形而不是两个圆形,对吗?
坦率地说,与其使用一个通用的.equals
方法,而不是仅使用==
运算符,不如将其改进,您应该为每个派生类实现它。
我不知道您的Rectangle
类是什么样子,但我将尝试一下:
public boolean equals(Object other) {
if (other == this) return true;
if (other == null) return false;
if (getClass() != other.getClass()) return false;
Rectangle rect = (Rectangle) other;
// compare measures of this and other Rectangle
return width == rect.width && height == rect.height;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.