In `equals(T value)`, must T be Object, or can it be like City, etc?

143 Views Asked by At

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

There are 3 best solutions below

3
On BEST ANSWER

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:

3
On

Don't take anything else than an Object if you want to override equals()!

Writing a specialized equals() method is a common error but tends to violate the equals() contract.

0
On

you can have both: (see poke's comment above)

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