是否必须在 hashCode() 和 equal() 方法中包含像 Hashset 这样的集合类型字段

Is it mandatory to include collection type fields like Hashset in hashCode() and equal() methods

在我的项目中,如果我们在 hashCode() 和 equal() 中包含集合字段,我已经看到性能问题 methods.Is 是否强制包含?下面是示例程序。

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;
}      

}

对于如何实施 equals()hashCode() 没有 "mandatory" 要求。好吧,我将在下面提到一个小要求。您可以以对您的应用程序有意义的任何方式实现它们。看起来您只需要考虑学生的 ID 号,因为这是让学生独一无二的原因。当然名称和 parents 不是唯一的。

只需确保 equals()hashCode() 都基于相同的字段,以便您履行所需的合同(这是唯一的 "required" 方面)。