2013-08-05 31 views
4

考慮我已經有String類成員一個POJO:如何通過結合其散列碼計算的POJO的hashCode的鍵

class POJO { 
    String name, address, emailId; 
    equals() { 

    } 
    hashCode() { 
    // How?  
    } 
} 

我如何能結合hashCode是我的琴絃,以形成一個POJO hashCode

+0

'返回31 + 7 * name.hashCode()+ 11 * address.hashCode()// ... etc' –

+2

日食:'源 - >生成的hashCode()和equals()'。 .. – jlordo

+1

Netbeans:'Alt + Insert - >生成hashCode()和equals()' –

回答

1

做這樣的:

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; 
} 
+1

你在'prime * result'上重複添加什麼?我認爲這不會爲'hashCode'添加任何內容。 –

+0

@BoristheSpider:只是爲了讓哈希碼唯一。 –

+0

@BoristheSpider:http://stackoverflow.com/questions/3613102/why-use-a-prime-number-in-hashcode –

15

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; 
} 
1

下面是一個相當不錯的哈希碼。

@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; 
    } 
6

您可以使用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(); 
}