[英]Is it sensible to use the hash code of a class as its serialVersionUID?
[英]How to use a String in an Entity class hash code?
我正在制作一個查詢SQL數據庫的Web應用程序。 我的印象是,我需要在整個站點上使用實體類和facade類來實現持久性。 實體類模板具有哈希碼和1.)我不確定是否需要它們,以及2.)如果需要,它們想要的是int,但我所擁有的都是String,那么如何將它們轉換為int然后又返回到String? 因為我需要將String值顯示在網站上,並且哈希值需要int的值。
繼承人的代碼(已刪除進口以保護無辜者...):
@Embeddable
public class ComputerOwnersPK implements Serializable {
@Basic(optional=false)
@NotNull
@Column(name="Computer_Name")
private int computerNameId;
@Basic(optional=false)
@NotNull
@Column(name="User_ID")
private int userId;
public ComputerOwnersPK() {
}
public ComputerOwnersPK(int computerNameId,int userId) {
this.computerNameId=computerNameId;
this.userId=userId;
}
public int getComputerNameId() {
return computerNameId;
}
public void setComputerNameId(int computerNameId) {
this.computerNameId=computerNameId;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId=userId;
}
@Override
public int hashCode() {
int hash=0;
hash+=(int) computerNameId;
hash+=(int) userId;
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if(!(object instanceof ComputerOwnersPK)) {
return false;
}
ComputerOwnersPK other=(ComputerOwnersPK) object;
if(this.computerNameId!=other.userId) {
return false;
}
if(this.userId!=other.userId) {
return false;
}
return true;
}
@Override
public String toString() {
return "entity.ComputerOwnersPK[ computerNameId="+computerNameId+", userId="+userId+" ]";
}
}
根據您的評論,我假設您希望computerNameId和userId在您的映射中為字符串,並且您將它們映射為ints,因為您不知道如何執行哈希碼。
在您的hashCode方法中,您應該能夠連接字符串,然后對它們調用哈希碼。 與您已經在做的非常相似。
private String computerNameId;
private String userId;
@Override
public int hashCode() {
// concatenate the interesting string fields
// and take the hashcode of the resulting String
return (computerNameId + userId).hashCode();
}
確保在equals方法中,您也從!=
運算符更改為!.equals
方法調用,以檢查相等性。 最后,請確保您保持equals和hashCode之間的契約,否則您可能會感到有些討厭。 兩個相等的對象也必須具有相同的hashCode。 具有相同hashCode的兩個對象可以相等也可以不相等。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.