java - java.util.HashSet 中的 contains() 方法的行为不符合我的预期

标签 java hashset

这是java main()方法:



    public static void main(String[] args) {
        
        HashSet set = new HashSet();
        Mapper test = new Mapper("asd", 0);
        set.add(test);
        
        System.out.println(new Mapper("asd", 0).equals(test));
        System.out.println(set.contains(new Mapper("asd", 0)));
        
    }

我的映射器类是:

class Mapper {

String word;
Integer counter;

Mapper (String word, Integer counter) {
    
    this.word = word;
    this.counter = counter;
    
}

public boolean equals(Object o) {
    
    if ((o instanceof Mapper) && (((Mapper)o).word == this.word)) {
        
        return true;
        
    }
    
    return false;
    
}

}

结果是:

true

false

从 HashSet 规范中,在这个方法中我读到了这样的内容:“如果此集合包含指定的元素,则返回 true。更正式地说,当且仅当此集合包含元素 e 且满足 (o==null ? e= =null : o.equals(e))."

那么,谁能解释一下我哪里错了?或者...?

谢谢。

最佳答案

您需要实现适当的 hashCode() 函数。

public int hashCode() {
  // equal items should return the same hashcode
}

Java 实用程序 java.util 包含许多依赖哈希的类。允许人们按照自己认为合适的方式重写 equals() 意味着人们还必须正确重写 hashCode() 才能匹配。

hashCode() 的正确实现将为任何两个 equals() 返回 true 的对象返回相同的哈希值。与哈希相关的函数在检查对象是否相等之前先检查哈希是否相等(以解决哈希冲突)。

关于java - java.util.HashSet 中的 contains() 方法的行为不符合我的预期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5726460/

相关文章:

Java 唤醒 hibernate 线程

java - 访问与工作目录相同级别的 .properties 文件

java - Eclipse不会在Liferay maven项目中生成父主题文件

java - Spring RequestBody Mapping 将所有属性映射为 null 值

c++ - 为什么 unordered_set 操作像计数和删除返回一个 size_type?

java - 使用 HashSet 时的奇怪行为

c# - HashSet 不删除对象

java - 如何在 Play 框架中执行查询(使用 Oracle 10g)

java - 为什么我的程序的 HashSet 顺序总是相同的?

java - 添加到 HashSet 时出现空指针异常