Java 在'equals(T value)`中,不能是Object,也不能像City,等等?
我试图更好地理解Java 在'equals(T value)`中,不能是Object,也不能像City,等等?,java,equals,referenceequals,Java,Equals,Referenceequals,我试图更好地理解equals()方法。我所看到的所有示例都是这样的: public class City { public boolean equals(Object other) { if (other instanceof City && other.getId().equals(this.id)) { return true; } // ... } } 该方法
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());
}
}
是,它必须是
对象
。否则,您不会覆盖真实,而是重载真实
如果您只是重载它,那么它将不会被标准API使用,例如
相关问题:
对象以外的任何对象
编写专门的equals()方法是一个常见错误,但往往会违反equals()约定。您可以同时使用这两种方法:(参见上面的poke评论)
并使用@Override
确保您没有犯错误。这是问题吗?它有什么作用?它的作用是你认为你写的equals方法不会被使用,但是你可以同时做这两件事,用一个特殊的equals(City)
方法重载它,这个方法专门检查两个城市,然后覆盖你将调用equals(City)的原始equals(Object)
方法
如果传递的对象是城市,则执行其他操作(如始终返回false)。@poke-+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());
}
}