java - 对象的哈希码是否有任何内部映射到我们在类中重写的内容

标签 java

集合关心唯一性,因此在程序中实现集合时,我们必须重写java.lang.Object equals()hashCode() 方法,这样我们就不会出现重复的情况。引用在 JVM 的单个当前实例的上下文中保持其有效性,记住这一点,我尝试以这种方式编码我的程序。在 TestSet.main 中(第 4-6 行)。我尝试通过在这些行中使用注释来以实用的方式提出我的查询。

class TestCase  {
    transient private int x;
    private int y;
    public TestCase(int x, int y) {
        this.x = x;
        this.y = y;
    }
    public boolean equals(Object o) {
        if (o instanceof TestCase && (((TestCase) o).getXValue() == getYValue()))
            return true;
        else
            return false;
    }
    public int hashCode() {
        return x + y;
    }
    public int getXValue() {
        return x;
    }
    public int getYValue() {
        return y;
    }
}

class TestSet {
    public static void main(String[] args) {
        TestCase tc1 = new TestCase(4, 8);
        TestCase tc2 = new TestCase(4, 8);
        Set<TestCase> set = new HashSet<TestCase>();
        set.add(tc1);//succeeds
        set.add(tc2);//succeeds
        System.out.println(set.add(tc2));//fails and gives us false.
        tc2 = new TestCase(4, 8);
        System.out.println(set.add(tc2));//succeeds and gives us true?
        System.out.println(set.size());
        System.out.println(set.contains(tc1));
        System.out.println(set.contains(tc2));
    }
}

最佳答案

您的 equals 方法中有一个拼写错误:您正在将一个元素的 x 与另一个元素的 y 进行比较。这几乎没有任何意义;您应该比较 x 和 y。

您应该将等于实现为

return o instanceof TestCase
   && ((TestCase) o).getXValue() == getXValue()
   && ((TestCase) o).getYValue() == getYValue();

第二个 .add(tc2) 返回 false 的原因是 HashSet 的实现使用 == 检查作为一种优化,并且恰好捕获了该特定情况。这不会改变 .equals 方法的缺陷。

关于java - 对象的哈希码是否有任何内部映射到我们在类中重写的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37058409/

相关文章:

java - 很确定我的循环过于复杂但不确定如何简化

java - 如何从java中的YAML文件中读取?

java - 将对象传递给新 Activity 返回 null

java - VideoView onTouch 事件 : pause/resume video, 和显示/隐藏 MediaController 和 ActionBar

java - 避免使用 Java 编写 HTML

java - 如何使用 Branch.io 实现推荐系统

java - 如何使用从 JFileChooser 选择的 Canvas 播放视频

java - 如何修复 java.io.InvalidClassException : org. springframework.security.core.context.SecurityContextImpl

java - 如何在java中只打开一个现有文件

java - 如何在显示JSP后执行hibernate session.close()以避免lazy=false