考慮我已經有String類成員一個POJO:如何通過結合其散列碼計算的POJO的hashCode的鍵
class POJO {
String name, address, emailId;
equals() {
}
hashCode() {
// How?
}
}
我如何能結合hashCode
是我的琴絃,以形成一個POJO hashCode
?
考慮我已經有String類成員一個POJO:如何通過結合其散列碼計算的POJO的hashCode的鍵
class POJO {
String name, address, emailId;
equals() {
}
hashCode() {
// How?
}
}
我如何能結合hashCode
是我的琴絃,以形成一個POJO hashCode
?
做這樣的:
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result
+ ((address == null) ? 0 : address.hashCode());
result = prime * result
+ ((emailId == null) ? 0 : emailId.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
你在'prime * result'上重複添加什麼?我認爲這不會爲'hashCode'添加任何內容。 –
@BoristheSpider:只是爲了讓哈希碼唯一。 –
@BoristheSpider:http://stackoverflow.com/questions/3613102/why-use-a-prime-number-in-hashcode –
Java 7中有個實用方法來創建一個散列碼,這是很好的大部分用途:
return Objects.hash(name, address, emailId);
你還需要確保你的equals方法是一致的。這兩種方法可能如下所示:
@Override
public int hashCode() {
return Objects.hash(name, address, emailId);
}
@Override
public boolean equals(Object obj) {
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
final POJO other = (POJO) obj;
if (!Objects.equals(this.name, other.name)) return false;
if (!Objects.equals(this.address, other.address)) return false;
if (!Objects.equals(this.emailId, other.emailId)) return false;
return true;
}
下面是一個相當不錯的哈希碼。
@Override
public int hashCode() {
int hash = 7;
hash = 29 * hash + Objects.hashCode(this.name);
hash = 29 * hash + Objects.hashCode(this.address);
hash = 29 * hash + Objects.hashCode(this.emailId);
return hash;
}
您可以使用org.apache.commons.lang.builder.HashCodeBuilder類,而不必擔心哈希碼implementation.It如下哈希碼和等於之間的合同。
對於你的班級,你必須做如下的實施。
@Override
public int hashCode(){
HashCodeBuilder builder = new HashCodeBuilder();
builder.append(name);
builder.append(address);
builder.append(emailId);
return builder.toHashCode();
}
'返回31 + 7 * name.hashCode()+ 11 * address.hashCode()// ... etc' –
日食:'源 - >生成的hashCode()和equals()'。 .. – jlordo
Netbeans:'Alt + Insert - >生成hashCode()和equals()' –