java - 如何为可选参数创建哈希码和等于

标签 java json guava optional-parameters optional-arguments

我想创建一个 RESTful Web 服务。我有一个用户类。我想创建多个 User 对象并将其存储在 HashMap 中以模拟数据库。因此,当客户端发送 PUT 请求时,基于 JSON 数据并从 JSON 中提取 ID,我可以在 hashmap 中执行操作以更新或删除。以下是重写 equals 和 hashcode 方法的正确方法吗?但问题是,如果 zip 或中间名为 null 或为空,会发生什么情况。每次创建对象时,构造函数中的 ID 都会递增。

public class User implements Serializable {

    private static final long serialVersionUID = 1L;
    private static final AtomicInteger ID = new AtomicInteger(0);

    private String firstName;
    private Optional<String> middleName;
    private String lastName;
    private int age;
    private Gender gender;
    private String phone;
    private Optional<String> zip;

    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }
        if (this.getClass() != obj.getClass()) {
            return false;
        }
        final User other = (User) obj;
        return Objects.equals(this.ID, other.ID)
                &&  Objects.equals(this.firstName, other.firstName)
                && Objects.equals(this.middleName, other.middleName)
                && Objects.equals(this.lastName, other.lastName)
                && Objects.equals(this.age, other.age)
                && Objects.equals(this.gender, other.gender)
                && Objects.equals(this.phone, other.phone)
                && Objects.equals(this.zip, other.zip);
    }

    @Override
    public int hashCode() {
        return Objects.hash(
                this.firstName, this.middleName, this.lastName, this.age, this.gender, this.phone, this.zip);

    }

    @Override
    public String toString() {
        return MoreObjects.toStringHelper(this)
                .add("firstName", this.firstName)
                .add("middleName", this.middleName)
                .add("lastName", this.lastName)
                .add("age", this.age)
                .add("gender", this.gender)
                .add("phone", this.phone)
                .add("zip", this.zip)
                .toString();
    }
}

最佳答案

Objects.equals(this.middleName.orElse(null), other.middleName.orElse(null))

关于java - 如何为可选参数创建哈希码和等于,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35964128/

相关文章:

java - 配置 JAXB 如何解码 boolean 值

java - 从 javadoc 绘制接口(interface)和类图的程序

Matlab webwrite 中的 JSON 负载

java - get JSONException : Value of type java. 解析 JSON 响应时 lang.String 无法转换为 JSONObject

java - Guava HashBiMap 的 containsValue 的大 O

java - 从 Guava RemovalListener 重新插入条目是否安全?

java - 我在使用 JavaFX 画十字时遇到问题

json - Json 和 Jsonp 有什么区别?

java - 是否可以使用 Java Guava 将函数应用于集合?

java - 带有递归的 WebCrawler