-1

I have a class with two fields:

String field1;
byte[] field2;

I would like to implement equals and hashCode functions for my class. I created equals using:

return Objects.equals(this.field1, aObj.field1) && Arrays.equals(this.field2, aObj.field2);

How would you implement hashCode since this does not work:

return Objects.hash(field1, field2); 

My best guess is:

return 37 * Objects.hashCode(field1) + Arrays.hashCode(field2);

Is there a more elegant way to do it, having potentially many array fields?

Full test class:

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;
        }
    }
}
Dominik Pawlak
  • 1,350
  • 9
  • 10

1 Answers1

0

Possible solution is use List<Byte> instead of byte[] and then that's correct way:

Objects.hashCode(field1, field2);
Dmitry Ginzburg
  • 7,391
  • 2
  • 37
  • 48