How to implement hashCode and equals method

Vidya picture Vidya · Jan 25, 2010 · Viewed 30.4k times · Source

How should I implement hashCode() and equals() for the following class in Java?

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

Answer

jutky picture jutky · Jan 25, 2010

in Eclipse right mouse click-> source -> generate hashCode() and equals() gives this:

/* (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);
}

I've selected code as a unique field