我有一个有两个字段的课程:
String field1;
byte[] field2;
我想为我的班级实施equals
和hashCode
函数。我使用:
equals
return Objects.equals(this.field1, aObj.field1) && Arrays.equals(this.field2, aObj.field2);
如何实施hashCode
,因为这不起作用:
return Objects.hash(field1, field2);
我最好的猜测是:
return 37 * Objects.hashCode(field1) + Arrays.hashCode(field2);
有没有更优雅的方法来实现它,可能有很多数组字段?
完整的测试课程:
public class EqualsTest {
public static void main(String[] args) {
AClass a = new AClass("aaa", new byte[] {10, 13, 15, 23});
AClass b = new AClass("bbb", new byte[] {10, 13, 15, 23});
AClass c = new AClass("aaa", new byte[] {10, 13, 15, 33});
AClass d = new AClass("aaa", new byte[] {10, 13, 15, 23});
System.out.println("a == b: " + a.equals(b));
System.out.println("a == c: " + a.equals(c));
System.out.println("a == d: " + a.equals(d));
System.out.println("a hash: " + a.hashCode());
System.out.println("b hash: " + b.hashCode());
System.out.println("c hash: " + c.hashCode());
System.out.println("d hash: " + d.hashCode());
}
private static class AClass {
String field1;
byte[] field2;
public AClass(String field1, byte[] field2) {
this.field1 = field1;
this.field2 = field2;
}
@Override
public int hashCode() {
// return Objects.hash(field1, field2);
return 37 * Objects.hashCode(field1) + Arrays.hashCode(field2);
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj instanceof AClass) {
AClass aObj = (AClass)obj;
return Objects.equals(this.field1, aObj.field1) && Arrays.equals(this.field2, aObj.field2);
}
return false;
}
}
}
答案 0 :(得分:0)
可能的解决方案是使用List<Byte>
代替byte[]
,然后采用正确的方式:
Objects.hashCode(field1, field2);