overriding equals and hashcode methods in java?

*爱你&永不变心* 提交于 2019-12-08 05:06:31

Edit:

public class Request implements Serializable{

     private String id;
     private String name;
     private String hid;

        public String getId()
        {
            return id;
        }

        public String getName()
        {
            return name;
        }

        public String getHid()
        {
            return hid;
        }
}

    public class EmpRequest implements Serializable{
         private Request request;

        public Request getRequest()
        {
            return request;
        }

         @Override 
         public boolean equals(Object obj) {
             if(obj==null)
                 return false;
             if(((EmpRequest) obj).getRequest().getId().equals(this.getRequest().getId()))
                 return true;
             else if(((EmpRequest) obj).getRequest().getName().equals(this.getRequest().getName())
                     &&((EmpRequest) obj).getRequest().getHid().equals(this.getRequest().getHid())) {
                 return true;
             }
             else
                 return false;
         }
    }

Here is the hashcode too:

@Override
public int hashCode()
{
    final int prime = 31;
    int result = 1;
    result = prime * result + ((getRequest().getId() == null) ? 0 : getRequest().getId().hashCode());
    result = prime * result + ((getRequest().getName() == null) ? 0 : getRequest().getName().hashCode());
    result = prime * result + ((getRequest().getHid() == null) ? 0 : getRequest().getHid().hashCode());
    return result;
}

you can just generate equals() and hashCode() from IDE (Eclipse, IntelliJ IDEA) . That will enough for your scenario.

@Override
public boolean equals(Object o) {
    if (this == o) return true;
    if (!(o instanceof Result)) return false;

    Result result = (Result) o;

    if (hid != null ? !hid.equals(result.hid) : result.hid != null) return false;
    if (id != null ? !id.equals(result.id) : result.id != null) return false;
    if (name != null ? !name.equals(result.name) : result.name != null) return false;

    return true;
}

@Override
public int hashCode() {
    int result = id != null ? id.hashCode() : 0;
    result = 31 * result + (name != null ? name.hashCode() : 0);
    result = 31 * result + (hid != null ? hid.hashCode() : 0);
    return result;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!