java - 在java中重写equals和hashcode方法?

标签 java hashcode java-ee-7

我有以下类(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 不相等,那么我需要检查 namehid 属性。 如果两个对象的 name 和 hid 属性相等,那么我需要返回 true。 否则为假

我怎样才能做到这一点?我尝试覆盖 equals()hashCode() 但 Eclipse 给了我以下警告。

The field type 'com.mycompany.Request' does not implement equals() and hashCode() - 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/

相关文章:

objective-c - 对于具有两个字符串和两个 BOOL 的对象,什么是好的散列?

java - 对于整数元组来说,什么是好的哈希函数?

wildfly - 如何配置相互证书身份验证

java - 使用 Ganymed SSH2 发送 SIGINT CTRL-C?

java - Juddi 发布和查找服务

java - 为什么哈希码不生成唯一的哈希码?

java - GlassFish 4 错误 : FATAL: FATAL: JSF1073: javax. el.ELException

java - 使用 hibernate 和 commit() 将数据保存在数据库中

java - 找不到类 MainActivity(导入的项目)

java - 如何在不扩展 Activity 的类中使用 getIntent()?