在Java中为我的对象实现Equals和hashCode
所以我知道这是被广泛谈论和讨论的,我只是想让我的等式适用于形状。我已经创建了一个类Shape,它说明了什么类型的形状(即矩形、三角形、圆形),如果它们是相同的形状,我会尝试返回true 主要用于测试在Java中为我的对象实现Equals和hashCode,java,object,equals,equality,Java,Object,Equals,Equality,所以我知道这是被广泛谈论和讨论的,我只是想让我的等式适用于形状。我已经创建了一个类Shape,它说明了什么类型的形状(即矩形、三角形、圆形),如果它们是相同的形状,我会尝试返回true 主要用于测试 Rectangle myRect = new Rectangle(3,5); Rectangle myRect2 = new Rectangle(3,5); if (myRect==myRect2){ System.out.println("B
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");
}
还有我的实际形状类,覆盖了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
仅当它们是相同的对象时才返回true
。您应该使用myRect.equals(myRect2)代码>在java中,当涉及到对象时,使用=
意味着检查对象的地址值。让我用一个例子来解释这一点:
Rectangle objA = new Rectangle(3,5);
Rectangle objB = objA;
此处在内存位置A上创建了objA
,并且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==这个
有点多余,因为如果前面的行返回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;
}
您认为other==this
有什么作用?您认为myRect==myRect2
有什么作用?您可能需要签出。