0

I know that I should implement hashCode() and equals(), however in reality I have no idea how to do it. I have a following class:

public class Dog {

   private Integer id;
   private Integer age;
   private Instant dateOfBirth;
}

And now, I would like to be able to check if some list of dogs is subset of another list of dogs.

ArrayList<Dog>

Two dogs I consider as equals when they have the same age, id, dateOfBirth

Ofcourse, it seems to be easy to implement equals:

public boolean equals(Dog dog) {
  return (dog.id == this.id && dog.age == dog.age && &this.dateOfBirth.equals(dog.dateOfBirth));
}

However, I have no idea how to implement hashCode to maintain equals-hashcode contract ?

Suryakant Bharti
  • 673
  • 1
  • 6
  • 24
  • isn't ID sufficient? As in if ID is unique and immutable for each dog, you don't need age and dateOfBirth (here one depends on another anyway, so use Instant as higher fidelity, if ID is not sufficient) – diginoise Jan 31 '20 at 11:48
  • 3
    @Tom.Reunick In your equals method you use `==` to compare `Integer` instances. This will only work for values that are part of the integer cache (-128 to 127). – OH GOD SPIDERS Jan 31 '20 at 11:48
  • 1
    Side note: Unless you want to accept `null`, use `int` instead of `Integer`. And if null is acceptable `this.dateOfBirth.equals` might crash with an NPE. Also not sure if `==` works properly for `Integer`. – Thilo Jan 31 '20 at 11:48
  • Interesting that `hashCode` would be used when determining if a list is a sublist of another one. How does that work? Do you have any reference for this algorithm? – Thilo Jan 31 '20 at 12:16

0 Answers0