简体   繁体   English

什么时候类应该是 Comparable 和/或 Comparator?

[英]When should a class be Comparable and/or Comparator?

I have seen classes which implement both Comparable and Comparator .我见过同时实现ComparableComparator 的类 What does this mean?这是什么意思? Why would I use one over the other?为什么我要使用一个?

The text below comes from Comparator vs Comparable下面的文字来自Comparator vs Comparable

Comparable可比

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.类本身必须实现java.lang.Comparable接口才能比较其实例。

Comparator比较器

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.这个比较器类必须实现java.util.Comparator接口。

Implementing Comparable means " I can compare myself with another object. " This is typically useful when there's a single natural default comparison.实现Comparable意味着“我可以将自己与另一个对象进行比较。 ”当存在单个自然默认比较时,这通常很有用。

Implementing Comparator means " I can compare two other objects. " This is typically useful when there are multiple ways of comparing two instances of a type - eg you could compare people by age, name etc.实现Comparator意味着“我可以比较两个其他对象。 ”当有多种方法比较一个类型的两个实例时,这通常很有用 - 例如,您可以按年龄、姓名等比较人。

Comparable lets a class implement its own comparison: Comparable 让一个类实现自己的比较:

  • it's in the same class (it is often an advantage)它在同一个班级(这通常是一个优势)
  • there can be only one implementation (so you can't use that if you want two different cases)只能有一个实现(所以如果你想要两种不同的情况,你就不能使用它)

By comparison, Comparator is an external comparison:通过比较,Comparator 是一个外部比较:

  • it is typically in a unique instance (either in the same class or in another place)它通常在一个唯一的实例中(在同一个类中或在另一个地方)
  • you name each implementation with the way you want to sort things你用你想要排序的方式命名每个实现
  • you can provide comparators for classes that you do not control您可以为您无法控制的类提供比较器
  • the implementation is usable even if the first object is null即使第一个对象为空,实现也可用

In both implementations, you can still choose to what you want to be compared .在这两种实现中,您仍然可以选择要比较的内容 With generics, you can declare so, and have it checked at compile-time.使用泛型,您可以声明,并在编译时检查它。 This improves safety, but it is also a challenge to determine the appropriate value.这提高了安全性,但确定合适的值也是一个挑战。

As a guideline, I generally use the most general class or interface to which that object could be compared, in all use cases I envision... Not very precise a definition though !作为指导方针,我通常使用可以与该对象进行比较的最通用的类​​或接口,在我设想的所有用例中......虽然不是很精确的定义! :-( :-(

  • Comparable<Object> lets you use it in all codes at compile-time (which is good if needed, or bad if not and you loose the compile-time error) ; Comparable<Object>允许您在编译时在所有代码中使用它(如果需要,这很好,否则就不好,并且您会丢失编译时错误); your implementation has to cope with objects, and cast as needed but in a robust way.您的实现必须处理对象,并根据需要但以健壮的方式进行转换。
  • Comparable<Itself> is very strict on the contrary.相反, Comparable<Itself>非常严格。

Funny, when you subclass Itself to Subclass, Subclass must also be Comparable and be robust about it (or it would break Liskov Principle, and give you runtime errors).有趣的是,当您将 Itself 子类化为 Subclass 时,Subclass 也必须是 Comparable 并且对此保持稳健(否则会破坏 Liskov 原则,并给您带来运行时错误)。

java.lang.Comparable java.lang.Comparable

  1. To implement Comparable interface, class must implement a single method compareTo()要实现Comparable接口,类必须实现单个方法compareTo()

    int a.compareTo(b)

  2. You must modify the class whose instance you want to sort.您必须修改要对其实例进行排序的类。 So that only one sort sequence can be created per class.这样每个类只能创建一个排序序列。

java.util.Comparator java.util.Comparator

  1. To implement Comparator interface, class must implement a single method compare()要实现 Comparator 接口,类必须实现单个方法compare()

    int compare (a,b)

  2. You build a class separate from class whose instance you want to sort.您构建一个与要对其实例进行排序的类分开的类。 So that multiple sort sequence can be created per class.这样可以为每个类创建多个排序序列。

Comparable is for providing a default ordering on data objects, for example if the data objects have a natural order. Comparable用于为数据对象提供默认排序,例如,如果数据对象具有自然顺序。

A Comparator represents the ordering itself for a specific use. Comparator代表特定用途的排序本身。

Comparable is usually preferred. Comparable的通常是首选。 But sometimes a class already implements Comparable , but you want to sort on a different property.但有时一个类已经实现了Comparable ,但您想要对不同的属性进行排序。 Then you're forced to use a Comparator .然后你被迫使用Comparator

Some classes actually provide Comparators for common cases;有些类实际上为常见情况提供了Comparators器; for instance, String s are by default case-sensitive when sorted, but there is also a static Comparator called CASE_INSENSITIVE_ORDER .例如, String在排序时默认区分大小写,但还有一个名为CASE_INSENSITIVE_ORDER的静态Comparator

here are few differences between Comparator and Comparable I found on web :我在网上找到了 Comparator 和 Comparable 之间的一些区别:

  1. If you see then logical difference between these two is Comparator in Java compare two objects provided to him, while Comparable interface compares "this" reference with the object specified.如果你看到那么这两者之间的逻辑区别是 Java 中的 Comparator 比较提供给他的两个对象,而 Comparable 接口将“this”引用与指定的对象进行比较。

  2. Comparable in Java is used to implement natural ordering of object. Java 中的 Comparable 用于实现对象的自然排序。 In Java API String, Date and wrapper classes implement Comparable interface.在 Java API String、Date 和 wrapper 类中,实现了 Comparable 接口。

  3. If any class implement Comparable interface in Java then collection of that object either List or Array can be sorted automatically by using Collections.sort() or Array.sort() method and object will be sorted based on there natural order defined by CompareTo method.如果任何类在 Java 中实现了 Comparable 接口,则可以使用 Collections.sort() 或 Array.sort() 方法自动对 List 或 Array 对象的集合进行排序,并且对象将根据 CompareTo 方法定义的自然顺序进行排序。

  4. Objects which implement Comparable in Java can be used as keys in a sorted map or elements in a sorted set for example TreeSet, without specifying any Comparator.在 Java 中实现 Comparable 的对象可以用作排序映射中的键或排序集中的元素,例如 TreeSet,无需指定任何 Comparator。

site:How to use Comparator and Comparable in Java?网站:如何在 Java 中使用 Comparator 和 Comparable? With example举例

Read more: How to use Comparator and Comparable in Java?阅读更多: 如何在 Java 中使用 Comparator 和 Comparable? With example 举例

Comparable is for objects with a natural ordering. Comparable适用于具有自然排序的对象。 The object itself knows how it is to be ordered.对象本身知道如何对其进行排序。
Comparator is for objects without a natural ordering or when you wish to use a different ordering. Comparator器适用于没有自然排序的对象,或者当您希望使用不同的排序时。

Difference between Comparator and Comparable interfaces Comparator 和 Comparable 接口之间的区别

Comparable is used to compare itself by using with another object. Comparable用于通过与另一个对象进行比较来比较自身。

Comparator is used to compare two datatypes are objects. Comparator器用于比较两种数据类型是对象。

If you see then logical difference between these two is Comparator in Java compare two objects provided to him, while Comparable interface compares "this" reference with the object specified.如果你看到那么这两者之间的逻辑区别是 Java 中的Comparator比较提供给他的两个对象,而Comparable接口将“this”引用与指定的对象进行比较。

Comparable in Java is used to implement natural ordering of object. Java 中的Comparable用于实现对象的自然排序。 In Java API String, Date and wrapper classes implement Comparable interface.在 Java API String、Date 和 wrapper 类中,实现了Comparable接口。

If any class implement Comparable interface in Java then collection of that object either List or Array can be sorted automatically by using Collections.sort() or Array.sort() method and object will be sorted based on there natural order defined by compareTo method.如果任何类在 Java 中实现了Comparable接口,那么可以使用Collections.sort()Array.sort()方法自动对ListArray对象的集合进行排序,并且对象将根据compareTo方法定义的自然顺序进行排序。

Objects which implement Comparable in Java can be used as keys in a sorted map or elements in a sorted set for example TreeSet , without specifying any Comparator .在 Java 中实现Comparable对象可以用作排序映射中的键或排序集中的元素,例如TreeSet ,而无需指定任何Comparator

My annotation lib for implementing Comparable and Comparator:我用于实现 Comparable 和 Comparator 的注释库:

public class Person implements Comparable<Person> {         
    private String firstName;  
    private String lastName;         
    private int age;         
    private char gentle;         

    @Override         
    @CompaProperties({ @CompaProperty(property = "lastName"),              
        @CompaProperty(property = "age",  order = Order.DSC) })           
    public int compareTo(Person person) {                 
        return Compamatic.doComparasion(this, person);         
    }  
} 

Click the link to see more examples.单击链接以查看更多示例。 compamatic 相伴的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM