我想创建一个 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/