0

In my project I have seen the performance issues if we include collection fields in hashCode() and equal() methods.Is it mandatory to include or not? Below is the sample program.

Student.java

public class Student {
    int no;
    String name;
    String adress;
    Set < Parent > parent;    
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((adress == null) ? 0 : 
       adress.hashCode());
        result = prime * result + ((name == null) ? 0 : name.hashCode());
        result = prime * result + no;
        result = prime * result + ((parent == null) ? 0 : 
       parent.hashCode());
        return result;
    }   
   public boolean equals(Object obj) {
    if (this == obj)
        return true;
    if (obj == null)
        return false;
    if (getClass() != obj.getClass())
        return false;
    Student other = (Student) obj;
    if (adress == null) {
        if (other.adress != null)
            return false;
    } else if (!adress.equals(other.adress))
        return false;
    if (name == null) {
        if (other.name != null)
            return false;
    } else if (!name.equals(other.name))
        return false;
    if (no != other.no)
        return false;
    if (parent == null) {
        if (other.parent != null)
            return false;
    } else if (!parent.equals(other.parent))
        return false;
    return true;
}      

}
user3094331
  • 532
  • 6
  • 21

1 Answers1

2

There is no "mandatory" requirements on how you implement equals() and hashCode(). Well, there is one slight requirement I'll mention below. You implement them in whatever way makes sense for your application. It looks like you need to consider only the student's ID number, as that is what makes students unique. Certainly names and parents are not unique.

Just make sure both equals() and hashCode() are based on the same fields so you fulfill the required contract (that is the only "required" aspect to this).

Jim Garrison
  • 85,615
  • 20
  • 155
  • 190
  • 1
    I think that you should be a bit more precise than "based on the same fields": they should be consistent, so that two objects for which `equals` is true also have equal `hashCode`s. – Andy Turner Feb 14 '18 at 07:48
  • Hi Jim, I got your point my question is if we include Set < Parent > parent in hashCode() and equals() methods it will degrade the performance. We are facing this issue in our application. After removing Set related varaibles from hashCode() and equals() method performance got improved. is this correct? – user3094331 Feb 15 '18 at 12:52
  • Yes, there's no need to include the `Set` in the comparison. – Jim Garrison Feb 15 '18 at 17:14