0

I am trying to implement RecyclerView ListAdapter with DiffUtils callback to only update/insert rows that has been changed not all. To implement I have to override these function from diff utils areItemsTheSame and areContentsTheSame. I can check areItemsTheSame using id of each object which I get from db. But for areContentsTheSame I don't want to write equals function and match each and every field with .equals method or similiar. I am wondering can I use default hashCode function from the class? If not can I override hashCode function like this?

public class Person {
  String name;
  String surname;
  String country;
  int age;    

  public Person(String name, String surname, String country, int age) {
      this.name = name;
      this.surname = surname;
      this.country = country;
      this.age = age;
  }

  @Override
  public int hashCode() {
      int prime=31;
      int sum = prime*this.name.hashCode();
      sum=sum+this.surname.hashCode();
      sum=sum+this.country.hashCode();
      sum=sum+this.age;
      return sum;
  }

}


Shahid Kamal
  • 380
  • 2
  • 14

1 Answers1

0

Java documentation states the following:

If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.

It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results.

Therefore, only using hashCode() function to check equality can give wrong results, given the probability that produced integers for different objects may have the same value.

If your concern is about having a long equals() method where every field is compared, you can only compare the fields that matters for equality.

Mehmed
  • 2,880
  • 4
  • 41
  • 62