java - 使用已经唯一的整数生成哈希码

标签 java hashcode hash-code-uniqueness

简单的问题。我有一个对象:

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/

相关文章:

java - 货币实用程序 Java 错误代码 'int java.lang.Object.hashCode()'

java - Eclipse 调试,更改 BigDecimal 上的变量值

java - Google map API 自行停止工作

java - 如何正确处理线程中断

java - 为什么我们不允许在java中重写枚举中的hashcode

java - 除了 Collections API 之外,在 Java 中覆盖 hashCode 有什么用?

java - 尝试使用字符串数组从类创建新对象

java - 是否可以在 java 中制作类似 Comparator 但用于实现自定义 equals() 和 hashCode()

java - 在java中实现好的hashCode函数?

java - 在 java 中传递对象时到底发生了什么?