java - 覆盖 hashCode 时要记住的事情

标签 java

public class Person {
    private String name, comment;
    private int age;

    public Person(String n, int a, String c) {
        name = n;
        age = a;
        comment = c;
    }

    public boolean equals(Object o) {
        if (!(o instanceof Person))
            return false;
        Person p = (Person) o;
        return age == p.age && name.equals(p.name);
    }
}

What is the appropriate definition of the hashCode method in class Person?

A. return super.hashCode();
B. return name.hashCode() + age * 7;
C. return name.hashCode() + comment.hashCode() / 2;
D. return name.hashCode() + comment.hashCode() / 2 - age * 3;

答案是B

谁能解释一下,为什么 C 和 D 是错误的?

最佳答案

对于 A、C 和 D,hashCode() 可能会为 Person 的 2 个实例返回不同的结果,其 equals() 方法返回true,即两个相同的 Person 可能会返回不同的哈希码。

这明显违反了Object.hashCode()的契约:

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.

对于 C 和 D,如果两个 Person 的年龄和姓名相同但评论不同,equals() 将返回 true,而 hashCode() 会产生不同的值。

对于 A,因为 Person 隐式继承自 Object 类(即它不从任何显式父类(super class)扩展),super.hashCode 的结果() 只有在同一实例上调用时才相等。根据 Object.hashCode() 文档:

As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the Java™ programming language.)

因此,如果您有 Person 类的两个不同实例,它们具有相同的名称、年龄和评论,equals() 将返回 true,而 hashCode() 会返回不同的值,这违反了 hashCode() 的约定。

实际上,这意味着 Person 类不能是任何 Map 的键。

关于java - 覆盖 hashCode 时要记住的事情,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29331336/

相关文章:

java - 如何将解密的文本文件字节 block 转储到 InputStreamReader 中?

java - 将 JMS 队列添加到 Jboss 7

未找到 Windows WinPlatformFactory 上的 JavaFx + Felix

java - 从类中读取字节

java - 插入子表时外键显示为空,错误无法将值 NULL 插入列中

java - 等待主框架加载时出现 JxBrowser TimeoutException (invokeAndWaitFinishLoadingMainFrame)

Javascript : Chrome dev tools OR NetBeans?

java - 要测试的正则表达式 '_'

java - 是否可以通过 Java 在 Android 中进行全景图像拼接?

Java实体插入DB更改列类型