等于对象的方法 [英] Equals method for objects

查看:118
本文介绍了等于对象的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为比较字段的对象编写一个equals方法,如果它们相等则返回true。

I'm trying to write an equals method for objects that compares their fields and return true if they're equal.

private int x, y, direction;
private Color color;

public boolean equals(Ghost other){
   if (this.x == other.x && this.y == other.y &&
       this.direction == other.direction && this.color == other.color)
      return true;
   else 
      return false;
}

这可能有什么问题?

推荐答案

由于颜色 似乎是一个 Color ,这是一个类,因此是一个引用类型,这意味着你需要使用 equals()比较颜色。

if (/* ... && */ this.color.equals(other.color)) {

如评论中所述,使用 == 比较引用类型实际上是在比较Java中的内存地址。它只返回 true ,如果它们都引用内存中的同一个对象。

As noted in the comments, using == to compare reference types is really comparing memory addresses in Java. It'll only return true if they both refer to the same object in memory.

akf指出您需要使用基地对象您的参数的类,否则您不会覆盖 Object.equals(),但实际上会重载它,即提供一种不同的方法来调用同名方法。如果碰巧偶然传递了一个完全不同的类的对象,可能会发生意外行为(尽管如果它们属于不同的类,它仍会正确返回 false )。

akf points out that you need to use the base Object class for your parameter, otherwise you're not overriding Object.equals(), but actually overloading it, i.e. providing a different way of calling the same-named method. If you happen to pass an object of a totally different class by accident, unexpected behavior might occur (although then again if they are of different classes it will return false correctly anyway).

@Override
public boolean equals(Object obj) {
    if (!(obj instanceof Ghost))
        return false;

    // Cast Object to Ghost so the comparison below will work
    Ghost other = (Ghost) obj;

    return this.x == other.x
        && this.y == other.y
        && this.direction == other.direction
        && this.color.equals(other.color);
}

这篇关于等于对象的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆