我可以使用实现hashCode()来实现我equals()的Java吗?或者这是一种不好的做法?
例如.,
public int hashCode()
{
// some computation based on the internal states
}
public equals(Object o)
{
return o instanceof ThisClass ? hashCode() == o.hashCode() : false;
}
Run Code Online (Sandbox Code Playgroud)
这是不好的做法.仅仅因为hashCodes相等并不意味着对象是平等的.
如果成员比较太贵,那么您可以使用hashCode初始检查来告诉您对象是否不相等.如果hashCodes匹配,你仍然需要进行成员比较.