我想使用自定义比较器从 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
类中的 equals
和 hashcode
方法
为什么会这样?
最佳答案
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/