在Java中为我的对象实现Equals和hashCode

时间:2014-11-15 00:44:34

标签: java object equals equality

所以我知道这被广泛讨论和讨论,我只是想让我的平等工作为Shapes。我已经创建了一个类Shape来说明什么类型的Shape,(即rect,triangle,circle),如果它们具有相同的形状,我会尝试返回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类,重写等于和哈希码。

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();
    }

基本上我的输出一直是假的,任何见解都会有所帮助,谢谢!

2 个答案:

答案 0 :(得分:2)

myRect==myRect2仅在它们是相同对象时返回true。您应该使用myRect.equals(myRect2);

答案 1 :(得分:1)

在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);

你没有对形状对象做任何事情,所以为什么要创建它,它只是为垃圾收集器做更多的工作。并且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;
}