两个字段组成的复合主键 hashcode equals 经典重写代码
假设有一个类,它有两个字段组成的复合主键,可以按照以下方式重写 hashCode 和 equals 方法:
public class MyClass {
private int key1;
private String key2;
public MyClass(int key1, String key2) {
this.key1 = key1;
this.key2 = key2;
}
@Override
public int hashCode() {
int result = 17;
result = 31 * result + key1;
result = 31 * result + (key2 != null ? key2.hashCode() : 0);
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
MyClass other = (MyClass) obj;
if (key1 != other.key1) return false;
if (key2 != null ? !key2.equals(other.key2) : other.key2 != null) return false;
return true;
}
}
在 hashCode 方法中,我们使用初值为 17 的 result 变量,然后将 key1 和 key2 字段的哈希码乘以 31 并加上 result,最后返回 result。这种方式可以避免哈希冲突的概率更大。
在 equals 方法中,我们首先检查是否是同一个对象,如果是则直接返回 true。然后检查传入的对象是否是同一类型,如果不是则返回 false。最后比较两个对象的 key1 和 key2 字段是否相等。注意,当 key2 字段为 null 时需要特殊处理,否则可能会抛出空指针异常
原文地址: https://www.cveoy.top/t/topic/edeS 著作权归作者所有。请勿转载和采集!