How calculate hashCode of a Pojo by combining hashCodes of it's keys

VishalDevgire picture VishalDevgire · Aug 5, 2013 · Viewed 9.7k times · Source

Consider i have one POJO having String class members :

class POJO {
  String name, address, emailId;
  equals() {

  }
  hashCode() {
    // How?    
  }
}

How can i combine hashCodes of my strings to form a hashCode for POJO?

Answer

assylias picture assylias · Aug 5, 2013

Java 7 has a utility method to create a hashcode which is good for most uses:

return Objects.hash(name, address, emailId);

You still need to make sure that your equals method is consistent. The two methods could look like:

@Override
public int hashCode() {
    return Objects.hash(name, address, emailId);
}

@Override
public boolean equals(Object obj) {
    if (obj == null) return false;
    if (getClass() != obj.getClass()) return false;
    final POJO other = (POJO) obj;
    if (!Objects.equals(this.name, other.name)) return false;
    if (!Objects.equals(this.address, other.address)) return false;
    if (!Objects.equals(this.emailId, other.emailId)) return false;
    return true;
}