How to implement hashCode and equals method

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


try this code, use 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();
}

Guava has helper methods for creating them. You tell it which fields to take in consideration and it will handle nulls for you and do the prime number calculation for hashcode.

IDEs can also generate them based on the fields you choose.

The advantage of delegating it to a tool like that is you get a standard solution and will worry less about bugs and maintenance of varied implementations spread all over your project.

Here's an example of using Guava and generated by an IntelliJ plugin: https://plugins.jetbrains.com/plugin/7244?pr=