I have below class.
public class Request implements Serializable {
private String id;
private String name;
private String hid;
// getters and setters
// This class does not override any equals() and hashCode() methods
}
public class EmpRequest implements Serializable {
private Request request;
//Now here in this class I need override equals() and hashCode() methods based on **request**
}
In EmpRequest class, I need to override equals()
and hashCode()
based on properties of Request object.
If two request objects id is equal then i need to return true. If two objects ids are not equal then i need to check for name and hid properties. If name and hid properties of both the objects are equals then i need to return true. Else false
How can I do that? I tried overriding equals()
and hashCode()
but eclipse gave me below the warning.
The field type 'com.mycompany.Request' does not implement
equals()
andhashCode()
- the resulting code may not work correctly.
At the same type I cannot modify Request class as I don't have control over it.
How can I write equals()
and hashCode()
considering above conditions?
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;
}