java - 为什么自定义比较器不能与 hashSet 一起使用来检查重复对象

标签 java eclipse hashset

我想使用自定义比较器从 HashSet 中过滤重复的对象。

Mobile 类中,我定义了一个非静态嵌套的Comparator 类用于比较。此比较器使用的标准是 Mobile 对象的 id 字段。

Set<Mobile> treeSet = new TreeSet<>(new Mobile().new Comparator()); // works


Set<Mobile> hashSet = new HashSet<>(new Mobile().new Comparator()); // does not work

尽管它非常适合 TreeSet,但当我尝试使用 HashSet 时,Eclipse 会显示语法错误,

看来,如果我想使用 HashSet,我需要覆盖 Mobile 类中的 equalshashcode 方法。但是,我更愿意使用比较器。

为什么会这样?

最佳答案

Hashset 设计为不接受重复项!。因此,如果您的集合不包含给定元素,它将把它添加到集合中。但是,如果在您的集合中出现这样的元素,则不会添加第二个(相同)元素并将其丢弃。

哈希集:

class offers constant time performance for the basic operations (add, remove, contains and size). it does not guarantee that the order of
elements will remain constant over time iteration performance depends on the initial capacity and the load factor of the HashSet. It's
quite safe to accept default load factor but you may want to specify
an initial capacity that's about twice the size to which you expect
the set to grow.

树集:

guarantees log(n) time cost for the basic operations (add, remove and contains) guarantees that elements of set will be sorted (ascending, natural, or the one specified by you via it's constructor) doesn't offer any tuning parameters for iteration performance offers a few handy methods to deal with the ordered set like first(), last(), headSet(), and tailSet() etc

要点:

Both guarantee duplicate-free collection of elements It is generally faster to add elements to the HashSet and then convert the collection to a TreeSet for a duplicate-free sorted traversal. None of these implementation are synchronized. That is if multiple threads access a set concurrently, and at least one of the threads modifies the set, it must be synchronized externally. LinkedHashSet is in some sense intermediate between HashSet and TreeSet. Implemented as a hash table with a linked list running through it, however it provides insertion-ordered iteration which is not same as sorted traversal guaranteed by TreeSet.

关于java - 为什么自定义比较器不能与 hashSet 一起使用来检查重复对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21362616/

相关文章:

java - 为什么 Sun Java 中的 HashSet 实现使用 HashMap 作为其后盾?

java - Scala 中可变 HashSet 类的更新方法

data-structures - 链式哈希集的负载因子

java - 启动 IntentService 的空指针异常

java每小时保存http post请求

java - 在 Windows Azure 模拟器中启动角色实例时出现无限循环 : [WaWorkerHost. exe] 已退出,错误代码为 1

eclipse - 不要在 Eclipse 中显示 .svn 文件夹

java - 列表接口(interface)排序方法和流接口(interface)排序方法有什么区别?

java - 从类似于 SQL LIKE '%search%' 的数组中过滤值

java - 如何以编程方式在 Eclipse 中刷新 Java 项目