java - 向 HashSet 输入有意义的相等数据

标签 java hashset

friend 们,我在HashSets中发现了这样一个问题。

public class _235 {
    private String s;
    public _235(String s){
    this.s=s;
    }
     public static void main(String[] args){

         HashSet<Object> hs=new HashSet<Object>();
         _235 ws1=new _235("ABC");
         _235 ws2=new _235("ABC");       

            String s1=new String("ABC");
            String s2=new String("ABC");

            hs.add(ws1);
            hs.add(ws2);
            hs.add(s1);
            hs.add(s2);

         System.out.println(hs.size());

     }
}

当我检查 ws1 和 ws1 都已添加到 HashSet 但不是从 s1 和 s2 中添加时,仅添加了一个字符串。由于 w1 和 w2 没有经过 equal() 我相信 HashSet 不会将它们识别为 equal 2 对象。但为什么字符串 s1 和 s2 的情况不一样呢?如何将它们识别为有意义的平等对象。请解释一下。

最佳答案

HashSet 要求您的自定义类重写在内部用于检测重复元素的 equals()hashcode() 方法。

String 类具有此实现,但您的自定义类 _235 没有此实现。

注意:重要的是要重写equals()hashcode(),而不仅仅是其中之一,否则结果可能是与基于哈希的集合一起使用时不可预测。

You must override hashCode() in every class that overrides equals(). Failure to do so will result in a violation of the general contract for Object.hashCode(), which will prevent your class from functioning properly in conjunction with all hash-based collections, including HashMap, HashSet, and Hashtable.

from Effective Java, by Joshua Bloch

这是一个link有很好的解释。

关于java - 向 HashSet 输入有意义的相等数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25227386/

相关文章:

java - 学习Java递归从书,Java完整引用

Java TreeMap 包含一个键但调用 containsKey 返回 false(即使键是完全相同的未更改对象)

c# - HashSet 允许重复项插入 - C#

java - 集合和哈希集 Java

java - 如何告诉 GridBagLayout 不要调整组件大小

java - 什么取代了 MongoDB AggregationOutput 类?

java - 无法将命令参数传递给 Java 调用的外部 .exe 应用程序

c++-cli - HashSet <T>在VS2012中哪里去了?

c# - .NET:如何有效地检查包含 50,000 个项目的 List<string> 中的唯一性?

java - HashSet Java 中的重复元素