How to implement hashCode and equals method

前端 未结 6 837
无人共我
无人共我 2020-12-01 12:08

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

class Emp 
{
  int empid ; // unique across all the         


        
6条回答
  •  生来不讨喜
    2020-12-01 12:56

    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

提交回复
热议问题