我有以下类(class)。
Request.java
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**
}
在 EmpRequest 类中,我需要根据 Request 的属性覆盖 equals()
和 hashCode()
> 对象。
如果两个请求对象id相等,那么我需要返回true。 如果两个对象 id 不相等,那么我需要检查 name 和 hid 属性。 如果两个对象的 name 和 hid 属性相等,那么我需要返回 true。 否则为假
我怎样才能做到这一点?我尝试覆盖 equals()
和 hashCode()
但 Eclipse 给了我以下警告。
The field type 'com.mycompany.Request' does not implement
equals()
andhashCode()
- the resulting code may not work correctly.
在同一类型中,我无法修改 Request 类,因为我无法控制它。
考虑到上述条件,我该如何编写equals()
和hashCode()
?
最佳答案
您可以从 IDE(Eclipse、IntelliJ IDEA)生成 equals()
和 hashCode()
。这对于你的场景来说已经足够了。
@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;
}
关于java - 在java中重写equals和hashcode方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20536890/