java - 对象的等于方法

标签 java object equals

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

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 appears to be一个Color ,这是一个类,因此是一个引用类型,这意味着您需要使用 equals() 来比较颜色。

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

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


akf points out你需要为你的参数使用基础 Object 类,否则你不是覆盖 Object.equals(),而是实际重载它,即提供不同的方式调用同名方法。如果您碰巧不小心传递了一个完全不同类的对象,则可能会发生意外行为(尽管如果它们属于不同类,它无论如何都会正确返回 false)。

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

关于java - 对象的等于方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3950439/

相关文章:

javascript - 合并数组中的重复对象

javascript - 如何将起点和终点坐标传递给 Google Maps directions API?

javascript - 在对象数组中添加对象(对象是多维的)

java - hashSet 如何接纳元素

java - BigDecimal 的规范表示

java - 如何按可能具有浮点值且没有适当等于的成员比较两个对象?

java - 从多个不同类型的用户输入创建一个数组

java - 如何通过 Spring 注释使用构建器模式

java - 检查 ConstraintViolationException 的原因

java - 如何在android xml文件和java文件中显示/隐藏TextView?