简单的问题。我有一个对象:
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;
}
无论如何,碰撞都是不可能的。
对吗?
最佳答案
Object.hashCode() javadoc告诉您回答问题所需了解的一切。
The general contract of hashCode is:
Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application.
If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.
It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hash tables.
关于java - 使用已经唯一的整数生成哈希码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22772550/