何时使用比较器和比较器
我有一个需要在字段上排序的对象列表,例如“分数”。没有多想,我编写了一个实现 Comparator 的新类,它完成了任务并且有效。
现在回过头来看,我想知道是否应该让我的类实现 Comparable,而不是创建一个实现 Comparator 的新类。分数是对对象进行排序的唯一字段。
我做了哪些可以接受的做法?
正确的方法是“首先让类实现 Comparable(为了自然排序),如果需要替代字段比较,然后创建一个实现 Comparator 的新类”吗?
如果上述(2)为真,那么是否意味着只有在类实现 Comparable 后才应该实现 Comparator? (假设我拥有原始类)。
I have a list of objects I need to sort on a field, say Score. Without giving much thought I wrote a new class that implements Comparator, that does the task and it works.
Now looking back at this, I am wondering if I should have instead have the my class implement Comparable instead of creating a new class that implements Comparator. The score is the only field that the objects will be ordered on.
What I have done acceptable as a practice?
Is the right approach "First have the class implement Comparable (for the natural ordering) and if an alternative field comparison is required, then create a new class that implements Comparator" ?
If (2) above is true, then does it mean that one should implement Comparator only after they have the class implement Comparable? (Assuming I own the original class).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(19)
使用
Comparable
如果您想定义相关对象的默认(自然)排序行为,常见的做法是使用技术或自然(数据库?)标识符为此的对象。使用
比较器
如果您想定义外部可控排序行为,这可以覆盖默认排序行为。另请参阅:
Use
Comparable
if you want to define a default (natural) ordering behaviour of the object in question, a common practice is to use a technical or natural (database?) identifier of the object for this.Use
Comparator
if you want to define an external controllable ordering behaviour, this can override the default ordering behaviour.See also:
我想说,如果这是对类进行排序的清晰自然的方式,则对象应该实现 Comparable,并且任何需要对类进行排序的人通常都希望这样做。
但是,如果排序是该类的不寻常用途,或者排序仅对特定用例有意义,那么比较器是更好的选择。
换句话说,给定类名,是否清楚可比较的排序方式,或者您是否必须求助于阅读 javadoc?如果是后者,很可能未来的每个排序用例都需要一个比较器,此时可比较的实现可能会减慢该类用户的速度,而不是加快他们的速度。
I would say that an object should implement Comparable if that is the clear natural way to sort the class, and anyone would need to sort the class would generally want to do it that way.
If, however, the sorting was an unusual use of the class, or the sorting only makes sense for a specific use case, then a Comparator is a better option.
Put another way, given the class name, is it clear how a comparable would sort, or do you have to resort to reading the javadoc? If it is the latter, odds are every future sorting use case would require a comparator, at which point the implementation of comparable may slow down users of the class, not speed them up.
使用
Comparable
:使用
Comparator
:Comparable
。Comparable
指定)行为不同的行为时。Use
Comparable
:Use
Comparator
:Comparable
.Comparable
) behaviour.可比较 -
java.lang.Comparable: intcompareTo(Object o1)
可比较对象能够将自身与另一个对象进行比较。类本身必须实现 java.lang.Comparable 接口,以便能够比较其实例。
仅一种排序序列
。EX:
Person.id
比较器 -
java.util.Comparator: int Compare(Object o1, Object o2)
比较器对象能够比较两个不同的对象。该类不是比较其实例,而是比较其他类的实例。该比较器类必须实现 java.util.Comparator 接口。
许多排序序列
并根据实例属性为每个排序序列命名。EX:
Person.id, Person.name, Person.age
示例:
对于 Java 8 Lambda:比较器,请参阅我的帖子。
Comparable -
java.lang.Comparable: int compareTo(Object o1)
A comparable object is capable of comparing itself with another object. The class itself must implements the java.lang.Comparable interface in order to be able to compare its instances.
only one sort sequence
based on the instances properties.EX:
Person.id
Comparator -
java.util.Comparator: int compare(Object o1, Object o2)
A comparator object is capable of comparing two different objects. The class is not comparing its instances, but some other class’s instances. This comparator class must implement the java.util.Comparator interface.
many sort sequence
and name each, based on the instances properties.EX:
Person.id, Person.name, Person.age
Example:
For Java 8 Lambda : Comparator refer to my post.
如果需要根据自然顺序对对象进行排序,则使用 Comparable,而如果需要根据不同对象的属性进行排序,则使用 Java 中的 Comparator。
Comparable 和 Comparator 之间的主要区别:
If sorting of objects needs to be based on natural order then use Comparable whereas if your sorting needs to be done on attributes of different objects, then use Comparator in Java.
Main differences between Comparable and Comparator:
当您比较同一类的实例时,应该使用 Comparable。
比较器可用于比较不同类的实例。
Comparable 是由需要为其对象定义自然顺序的类实现的。
例如,String 实现了 Comparable。
如果需要不同的排序顺序,则实现比较器并定义其自己的比较两个实例的方式。
Comparable should be used when you compare instances of the same class.
Comparator can be used to compare instances of different classes.
Comparable is implemented by the class which needs to define a natural ordering for its objects.
For example, String implements Comparable.
In case a different sorting order is required, then, implement comparator and define its own way of comparing two instances.
比较器可以完成同类功能的所有功能,甚至更多。
我找到了将比较器用作匿名类的最佳方法,如下所示:
您可以在计划排序的类中创建此类方法的多个版本。所以你可以有:
sortAccountsByPriorityAndType
etc...
现在,您可以在任何地方使用这些排序方法并实现代码重用。
这给了我所有可比较的东西,再加上更多......所以我根本不认为有任何理由使用可比较的东西。
Comparator does everything that comparable does, plus more.
I found the best approach to use comparators as anonymous classes as follows:
You can create multiple versions of such methods right inside the class you’re planning to sort. So you can have:
sortAccountsByPriorityAndType
etc...
Now, you can use these sort methods anywhere and get code reuse.
This gives me everything a comparable would, plus more ... so I don’t see any reason to use comparable at all.
我想说:
明确的,因此对于必须维护代码的可怜的灵魂来说更清楚,
可能是通过要比较的类中的工厂方法构建的。
I would say:
explicit and thus more clear for the poor soul who has to maintain the code
possibly build by a factory method in the class to be compared.
以下几点可帮助您决定在哪种情况下应使用 Comparable 以及哪种 Comparator:
1) 代码可用性
2) 单个与多个排序标准
3) Arays.sort() 和 Collection.sort()
4) 作为 SortedMap 和 Collection 中的键SortedSet
5) 更多类数与灵活性
6) 类间比较
7) 自然顺序
有关更详细的文章,您可以参考 何时使用比较器以及何时使用比较器
The following points help you in deciding in which situations one should use Comparable and in which Comparator:
1) Code Availabilty
2) Single Versus Multiple Sorting Criteria
3) Arays.sort() and Collection.sort()
4) As keys in SortedMap and SortedSet
5) More Number of classes Versus flexibility
6) Interclass comparisions
7) Natural Order
For more detailed article you can refer When to use comparable and when to use comparator
如果你需要自然顺序排序——User Comparable
如果您需要自定义顺序排序 - 使用比较器
示例:
自然顺序排序将基于 ID,因为它是唯一的,而自定义顺序排序将是名称和部门。
参考资料:
什么时候类应该是 Comparable 和/或 Comparator?< /a>
http://javarevisited.blogspot.com/2011/ 06/comparator-and-comparable-in-java.html
If you need natural order sorting -- User Comparable
IF you need Custom Order Sorting - Use Comparator
Example:
Natural order Sorting would be based on id because it would be unique and custom order sortin g would be name and department.
Refrences:
When should a class be Comparable and/or Comparator?
http://javarevisited.blogspot.com/2011/06/comparator-and-comparable-in-java.html
您只有一个排序用例
使用比较。
排序策略实施a
比较器。
you have only one use case of sorting
use Comparable.
strategy of sorting implement a
Comparator.
这里有一个类似的问题:何时应该一个类是可比较的和/或比较器?
我会说以下内容:
为自然排序之类的东西实现 Comparable,例如基于内部 ID。
如果您有更复杂的比较算法(例如多个字段等),则实现 Comparator。
There had been a similar question here: When should a class be Comparable and/or Comparator?
I would say the following:
Implement Comparable for something like a natural ordering, e.g. based on an internal ID
Implement a Comparator if you have a more complex comparing algorithm, e.g. multiple fields and so on.
可比较:
每当我们只想存储同类元素并需要默认的自然排序顺序时,我们可以使用实现
comparable
接口的类。比较器:
每当我们想要存储同质和异构元素并且想要按照默认的自定义排序顺序进行排序时,我们可以使用
comparator
接口。Comparable:
Whenever we want to store only homogeneous elements and default natural sorting order required, we can go for class implementing
comparable
interface.Comparator:
Whenever we want to store homogeneous and heterogeneous elements and we want to sort in default customized sorting order, we can go for
comparator
interface.我的需求是根据日期排序的。
所以,我使用了 Comparable,它对我来说很容易工作。
Comparable 的一项限制是它们不能用于除 List 之外的 Collections。
My need was sort based on date.
So, I used Comparable and it worked easily for me.
One restriction with Comparable is that they cannot used for Collections other than List.
如果您拥有该课程,最好选择可比较。通常,如果您不拥有该类,则使用 Comparator,但必须将其使用 TreeSet 或 TreeMap,因为 Comparator 可以作为参数传递TreeSet 或 TreeMap 的构造函数。您可以在 http://preciselyconcise.com/java/collections/g_comparator 中了解如何使用 Comparator 和 Comparable .php
If you own the class better go with Comparable. Generally Comparator is used if you dont own the class but you have to use it a TreeSet or TreeMap because Comparator can be passed as a parameter in the conctructor of TreeSet or TreeMap. You can see how to use Comparator and Comparable in http://preciselyconcise.com/java/collections/g_comparator.php
在一次采访中,我被要求在比 nlogn 更好的时间内对一定范围的数字进行排序。 (不使用计数排序)
在对象上实现 Comparable 接口允许隐式排序算法使用重写的compareTo 方法来对元素进行排序,这将是线性时间。
I have been asked sorting of a definite range of numbers in better than nlogn time in one of interview. (Not using Counting sort)
Implementing Comparable interface over an object allows implicit sorting algos to use overridden compareTo method to order sort elements and that would be linear time.
Comparable 是默认的自然排序顺序,数值按升序排列,字符串按字母顺序排列。
例如:
Comparator 是通过重写比较方法在自定义 myComparator 类中实现的自定义排序顺序
例如:
Comparable is the default natural sorting order provided for numerical values are ascending and for strings are alphabetical order.
for eg:
Comparator is the custom sorting order implemented in custom myComparator class by overriding a compare method
for eg:
非常简单的方法是假设所讨论的实体类在数据库中表示,然后在数据库表中您是否需要由实体类的字段组成的索引?如果答案是肯定的,则实现可比较并使用索引字段进行自然排序。在所有其他情况下使用比较器。
Very simple approach is to assume that the entity class in question be represented in database and then in database table would you need index made up of fields of entity class? If answer is yes then implement comparable and use the index field(s) for natural sorting order. In all other cases use comparator.
我的用于实现
Comparable
和Comparator
的注释库:单击链接查看更多示例。
http://code.google.com/p/compamatic/wiki/CompamaticByExamples
My annotation lib for implementing
Comparable
andComparator
:Click the link to see more examples.
http://code.google.com/p/compamatic/wiki/CompamaticByExamples