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

时间:2016-03-12 22:32:13

标签: java json guava optional-parameters optional-arguments

我想创建一个RESTful Web服务。我有一个用户类。我想创建多个User对象并将其存储在hashmap中以模拟数据库。因此,当客户端基于JSON数据发送PUT请求并从JSON中提取ID时,我可以在hashmap中执行操作以进行更新或删除。以下是覆盖equals和hashcode方法的正确方法。但问题是如果zip或middlename为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();
    }
}

1 个答案:

答案 0 :(得分:0)

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