排序集合的Java对象排序

当我查看Java Object Ordering教程时,文章的最后一节“比较器”让我感到困惑.

通过定义一个类Employee,它本身可以通过员工的名称进行比较,本教程不会显示此类是否覆盖了equals方法.然后,它使用自定义的Comparator,其中员工按资历分类,以对员工列表进行排序,并且我可以理解.

然后教程解释了为什么这对于排序集合(例如TreeSet(SortedSet))不起作用,原因是:

it generates an ordering that is not compatible with equals. This means that this Comparator equates objects that the equals method does not. In particular, any two employees who were hired on the same date will compare as equal. When you’re sorting a List, this doesn’t matter; but when you’re using the Comparator to order a sorted collection, it’s fatal. If you use this Comparator to insert multiple employees hired on the same date into a TreeSet, only the first one will be added to the set; the second will be seen as a duplicate element and will be ignored.

现在我很困惑,因为我知道List允许重复元素,而Set不基于equals方法.所以我想知道教程是否说比较器产生的排序与equals不兼容,这是什么意思?它还说’如果您使用此Comparator将在同一日期雇用的多名员工插入TreeSet,则只会将第一个添加到该集中;第二个将被视为重复元素,将被忽略.我不明白使用Comparator会如何影响原始equals方法的使用.我想我的问题是如何在这种情况下生成和排序TreeSet以及何时使用compare和equals方法.

解决方法:

So I wonder when the tutorial says the ordering generated by the Comparator is not compatible with equals, what does it mean?

在此示例中,Comparator仅根据资历来比较两个Employee对象.此比较不以任何方式使用equals或hashCode.记住这一点,当我们将此Comparator传递给TreeSet时,该集合将从Comparator中将0的任何结果视为相等.因此,如果任何员工共享起始日期,则只会添加一个,因为该集合认为它们是相等的.

最后:

I think my question is how the TreeSet will be produced and sorted in this case and when the compare and equals methods are used.

对于TreeSet,如果给出了Comparator,它使用compare方法来确定对象的相等性和排序.如果没有给出Comparator,那么set使用被排序对象的compareTo方法(它们必须实现Comparable).

Java规范声称所使用的compare / compareTo方法必须与equals一致的原因是因为Set规范使用了equals,即使这种特定类型的Set(TreeSet)使用了比较.

如果从某个方法实现中收到Set,则可以预期equals方法定义的该Set中没有对象的重复项.但是,因为TreeSet不使用此方法,所以开发人员必须小心确保比较方法产生与equals相同的相等性.

上一篇:一.生成10个1到20之间的不重复的随机数并降序输出


下一篇:java – TreeSet:有效小于值的元素数