如何实现哈希码和等于方法

2022-09-01 17:24:09

我应该如何在Java中实现和以下类?hashCode()equals()

class Emp 
{
  int empid ; // unique across all the departments 
  String name;
  String dept_name ;
  String code ; // unique for the department 
}

答案 1

在 Eclipse 中,鼠标右键单击>源 ->生成 hashCode() 和 equals() 给出:

/* (non-Javadoc)
 * @see java.lang.Object#hashCode()
 */
@Override
public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + (code == null ? 0 : code.hashCode());
    return result;
}
/* (non-Javadoc)
 * @see java.lang.Object#equals(java.lang.Object)
 */
@Override
public boolean equals(Object obj) {
    if (this == obj)
        return true;
    if (obj == null)
        return false;
    if (!(obj instanceof Emp))
        return false;
    Emp other = (Emp) obj;
    return code == null ? other.code == null : code.equals(other.code);
}

我已选择代码作为唯一字段


答案 2

试试这个代码,使用 org.apache.commons.lang3.builder

public int hashCode() {
    return new HashCodeBuilder(17, 31). // two randomly chosen prime numbers
        append(empid).
        append(name).
        append(dept_name ).
        append(code ).
        toHashCode();
}

public boolean equals(Object obj) {

    if (obj == this)
        return true;
    if (!(obj instanceof Person))
        return false;

    Emp rhs = (Emp) obj;
    return new EqualsBuilder().
        // if deriving: appendSuper(super.equals(obj)).
        append(name, rhs.name).
        isEquals();
}

推荐