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