2

I'm trying to understand the equals() method better. All examples I've seen do something like:

public class City
{
    public boolean equals(Object other)
    {
        if (other instanceof City && other.getId().equals(this.id))
        {
            return true;
        }

        // ...
    }
}

Must the method take on Object and not a City?

E.g. is this below not allowed?

public class City
{
    public boolean equals(City other)
    {
        if (other == null)
        {
            return false;
        }

        return this.id.equals(other.getId());
    }
}
4

3 回答 3

6

Yes, it must be an Object. Else you're not overriding the real Object#equals(), but rather overloading it.

If you're only overloading it, then it won't be used by the standard API's like Collection API, etc.

Related questions:

于 2010-07-17T16:34:06.547 回答
1

你可以同时拥有:(见上面戳的评论)

public class City
{
    public boolean equals(Object other)
    {
        return (other instanceof City) && equals((City)other) ;
    }
    public boolean equals(City other)
    {
        return other!=null && this.id.equals(other.getId());
    }
}
于 2010-07-17T17:20:09.283 回答
0

Object如果你想覆盖 equals(),除了 an 之外别无他法!

编写专门的 equals() 方法是一个常见错误,但往往会违反 equals() 协定。

于 2010-07-17T16:34:29.317 回答