Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 556
VishalDevgire Avatar asked Aug 05 '13 07:08

VishalDevgire


1 Answers

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;
}
like image 89
assylias Avatar answered Nov 02 '22 23:11

assylias