Java 何时使用 Comparable 和 Comparator

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2266827/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 05:27:14  来源:igfitidea点击:

When to use Comparable and Comparator

javacomparatorcomparable

提问by pkrish

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.

我有一个需要在字段上排序的对象列表,比如 Score。我没有多想就写了一个实现 Comparator 的新类,它可以完成任务并且可以工作。

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.

现在回想起来,我想知道我是否应该让我的类实现 Comparable,而不是创建一个实现 Comparator 的新类。分数是唯一可以对对象进行排序的字段。

  1. What I have done acceptable as a practice?

  2. 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" ?

  3. 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).

  1. 我做了什么可以接受的做法?

  2. 正确的方法是“首先让类实现 Comparable(用于自然排序),如果需要替代字段比较,然后创建一个实现 Comparator 的新类”?

  3. 如果上面的(2)是正确的,那么是否意味着只有在类实现了 Comparable 之后才应该实现 Comparator ?(假设我拥有原始类)。

采纳答案by Yishai

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.

我会说一个对象应该实现 Comparable 如果这是对类进行排序的清晰自然的方式,并且任何需要对类进行排序的人通常都希望这样做。

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.

但是,如果排序是类的不寻常使用,或者排序仅对特定用例有意义,那么 Comparator 是更好的选择。

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.

换句话说,给定类名,是否清楚可比较的排序方式,还是必须求助于阅读 javadoc?如果是后者,很可能每个未来的排序用例都需要比较器,此时可比较的实现可能会减慢该类的用户的速度,而不是加快他们的速度。

回答by ZeissS

There had been a similar question here: When should a class be Comparable and/or Comparator?

这里曾经有一个类似的问题:一个类什么时候应该是 Comparable 和/或 Comparator?

I would say the following: Implement Comparable for something like a natural ordering, e.g. based on an internal ID

我会说以下内容:为诸如自然排序之类的东西实现 Comparable,例如基于内部 ID

Implement a Comparator if you have a more complex comparing algorithm, e.g. multiple fields and so on.

如果您有更复杂的比较算法,例如多个字段等,请实现 Comparator。

回答by BalusC

Use Comparableif 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.

使用Comparable,如果要定义一个默认的(天然)排序问题的对象的行为,常见的做法是使用的技术或自然(数据库?)的对象标识符这一点。

Use Comparatorif you want to define an external controllableordering behaviour, this can override the default ordering behaviour.

使用Comparator如果要定义一个外部可控有序的行为,这可以覆盖默认排序行为。

回答by Bozho

Use Comparable:

使用Comparable

  • if the object is in your control.
  • if the comparing behaviour is the main comparing behaviour.
  • 如果对象在您的控制之下。
  • 如果比较行为是主要的比较行为。

Use Comparator:

使用Comparator

  • if the object is outside your control and you cannot make them implement Comparable.
  • when you want comparing behaviour different from the default (which is specified by Comparable) behaviour.
  • 如果对象不在您的控制范围内并且您无法让它们实现Comparable
  • 当您想要比较与默认(由 指定Comparable)行为不同的行为时。

回答by extraneon

I would say:

我会说:

  • if the comparison is intuitive, then by all means implement Comparable
  • if it is unclear wether your comparison is intuitive, use a Comparator as it's more explicit and thus more clear for the poor soul who has to maintain the code
  • if there is more than one intuitive comparison possible I'd prefer a Comparator, possibly build by a factory method in the class to be compared.
  • if the comparison is special purpose, use Comparator
  • 如果比较直观,那么一定要实现 Comparable
  • 如果不清楚您的比较是否直观,请使用比较器,因为它更明确,因此对于必须维护代码的可怜人来说更清晰
  • 如果可能有多个直观的比较,我更喜欢比较器,可能由要比较的类中的工厂方法构建。
  • 如果比较是特殊目的,请使用 Comparator

回答by fabrizioM

  • If at the moment of writing the class you have only one use case of sorting use Comparable.
  • Only when you have more than one strategy of sorting implement a Comparator.
  • 如果在编写课程时您只有一个排序用例,请使用 Comparable。
  • 只有当您有多个排序策略时,才实施 Comparator。

回答by Devang Paliwal

Comparable should be used when you compare instances of same class.

当您比较同一类的实例时,应使用 Comparable。

Comparator can be used to compare instances of different classes.

比较器可用于比较不同类的实例。

Comparable is implemented by class which need to define a natural ordering for its objects. Like String implements Comparable.

Comparable 是由需要为其对象定义自然顺序的类实现的。就像 String 实现了 Comparable。

In case one wants a different sorting order then he can implement comparator and define its own way of comparing two instances.

如果想要不同的排序顺序,那么他可以实现比较器并定义自己的比较两个实例的方式。

回答by user976715

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.

非常简单的方法是假设有问题的实体类在数据库中表示,然后在数据库表中您是否需要由实体类的字段组成的索引?如果答案是肯定的,则实现可比较并使用索引字段进行自然排序。在所有其他情况下使用比较器。

回答by Rajiv

If you need natural order sorting -- User Comparable IF you need Custom Order Sorting - Use Comparator

如果您需要自然顺序排序 - User Comparable 如果您需要自定义顺序排序 - 使用比较器

Example:

例子:

Class Employee{
private int id;
private String name;
private String department;
}

Natural order Sorting would be based on id because it would be unique and custom order sortin g would be name and department.

自然顺序排序将基于 id,因为它是唯一的,而自定义顺序排序将是姓名和部门。

Refrences:
When should a class be Comparable and/or Comparator?http://javarevisited.blogspot.com/2011/06/comparator-and-comparable-in-java.html

参考:
什么时候一个类应该是 Comparable 和/或 Comparator?http://javarevisited.blogspot.com/2011/06/comparator-and-comparable-in-java.html

回答by G swamy reddy

Comparable:
Whenever we want to store only homogeneous elements and default natural sorting order required, we can go for class implementing comparableinterface.

Comparable:
每当我们只想存储同质元素和所需的默认自然排序顺序时,我们可以去类实现 comparable接口。

Comparator:
Whenever we want to store homogeneous and heterogeneous elements and we want to sort in default customized sorting order, we can go for comparatorinterface.

Comparator:
每当我们要存储同质和异质元素并且我们想按照默认的自定义排序顺序进行排序时,我们可以去comparator接口。