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