簡單的問題。我有一個對象:用已經唯一的整數生成哈希碼
class User {
int id;
String username;
public User() {
}
public User(int id, String username) {
this.id = id;
this.username = username;
}
@Override
public String toString() {
return id + " - " + username;
}
@Override
public int hashCode() {
int hash = 7;
hash = 31 * hash + this.id;
return hash;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final User other = (User) obj;
return this.id == other.id;
}
public void setUsername(String username) {
this.username = username;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public int getId() {
return id;
}
}
基於int id
確定了它們的平等(這是一個數據庫ID)。
的Netbeans自動生成該hashCode()
方法:
@Override
public int hashCode() {
int hash = 7;
hash = 31 * hash + this.id;
return hash;
}
的問題是:是否有任何優勢,這在剛剛返回(已經)獨特int id
?
@Override
public int hashCode() {
return id;
}
碰撞是不可能的。
,對嗎?
hashCode的目標()不以避免碰撞。 –
從某種角度來看,它取決於你如何實現equals。如果你想添加一個數據值的克隆呢? – Rogue
[Joshua Block:Effective Java](http://uet.vnu.edu.vn/~chauttm/e-books/java/Effective.Java.2nd.Edition.May.2008.3000th.Release.pdf),Item 9 –