[英]how to create hashcode and equals for optional parameters
我想創建一個RESTful Web服務。 我有一個用戶類別。 我想創建多個User對象並將其存儲在哈希圖中以模擬數據庫。 因此,當客戶端基於JSON數據發送PUT請求並從JSON中提取ID時,我可以在哈希圖中執行操作以進行更新或刪除。 以下是重寫equals和hashcode方法的正確方法。 但是問題是,如果郵政編碼或中間名為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))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.