在`equals(T value)`中,T必须是Object,还是可以像City等?
我试图更好地理解 equals()
方法。我见过的所有示例都执行以下操作:
public class City
{
public boolean equals(Object other)
{
if (other instanceof City && other.getId().equals(this.id))
{
return true;
}
// ...
}
}
该方法必须采用对象而不是城市吗?
例如,下面的内容是不允许的吗?
public class City
{
public boolean equals(City other)
{
if (other == null)
{
return false;
}
return this.id.equals(other.getId());
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,它必须是一个
对象
。否则你就不会覆盖真实Object#equals()
,而是重载它。如果您只是重载它,那么它不会被标准 API 使用,例如 Collection API等。
相关问题:
equals()
?equals()
和hashCode()
?Yes, it must be an
Object
. Else you're not overriding the realObject#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:
equals()
?equals()
andhashCode()
?你可以两者兼得:(参见上面的 poke 评论)
you can have both: (see poke's comment above)
如果您想重写 equals(),请不要使用
Object
以外的任何内容!编写专门的 equals() 方法是一个常见错误,但往往会违反 equals() 约定。
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.