实际开发我们有时需要判断比较两个对象是否相同,通常做法是重写对象的equals方法。
但重写equals方法时,一般我们也会重写hashCode方法。其实如果该对象不会当作Map里的key,不重写hashCode方法也是没啥影响的。
想重写hashCode方法不知道该怎么写?下面是重写equals方法时,也重写hashCode方法的通用写法:
final class ResourceCacheKey implements Key {
private final Key sourceKey;
private final Key signature;
private final int width;
private final int height;private final Options options;
@Override
public boolean equals(Object o) {
if (o instanceof ResourceCacheKey) {
ResourceCacheKey other = (ResourceCacheKey) o;
return height == other.height && width == other.width&& sourceKey.equals(other.sourceKey)
&& signature.equals(other.signature)
&& options.equals(other.options);
}
return false;
}
@Override
public int hashCode() {
int result = sourceKey.hashCode();
result = 31 * result + signature.hashCode();
result = 31 * result + width;
result = 31 * result + height;
result = 31 * result + options.hashCode();
return result;
}
}