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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1440134/
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-12 12:17:49  来源:igfitidea点击:

When should a class be Comparable and/or Comparator?

javacomparatorcomparable

提问by Nick Heiner

I have seen classes which implement both Comparableand Comparator. What does this mean? Why would I use one over the other?

我见过同时实现ComparableComparator 的类。这是什么意思?为什么我要使用一个?

采纳答案by Dan

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.Comparableinterface 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.Comparatorinterface.

比较器对象能够比较两个不同的对象。该类不是比较它的实例,而是比较其他一些类的实例。这个比较器类必须实现java.util.Comparator接口。

回答by starblue

Comparableis for providing a default ordering on data objects, for example if the data objects have a natural order.

Comparable用于提供数据对象的默认排序,例如,如果数据对象具有自然顺序。

A Comparatorrepresents the ordering itself for a specific use.

AComparator代表特定用途的排序本身。

回答by Jon Skeet

Implementing Comparablemeans "I can compare myself with another object." This is typically useful when there's a single natural default comparison.

实现Comparable意味着“我可以将自己与另一个对象进行比较。”当存在单个自然默认比较时,这通常很有用。

Implementing Comparatormeans "I can compare two other objects." This is typically useful when there are multiple ways of comparing two instances of a type - e.g. you could compare people by age, name etc.

实现Comparator意味着“我可以比较两个其他对象。”当有多种方法比较一个类型的两个实例时,这通常很有用 - 例如,您可以按年龄、姓名等比较人。

回答by Michael Myers

Comparableis usually preferred. But sometimes a class already implements Comparable, but you want to sort on a different property. Then you're forced to use a Comparator.

Comparable通常是首选。但有时一个类已经实现了Comparable,但您想对不同的属性进行排序。然后你被迫使用Comparator.

Some classes actually provide Comparatorsfor common cases; for instance, Strings are by default case-sensitive when sorted, but there is also a static Comparatorcalled CASE_INSENSITIVE_ORDER.

有些类实际上提供Comparators了常见的情况;例如,Strings 在排序时默认区分大小写,但也有一个Comparator名为CASE_INSENSITIVE_ORDER.

回答by Michael Lloyd Lee mlk

Comparableis for objects with a natural ordering. The object itself knows how it is to be ordered.
Comparatoris for objects without a natural ordering or when you wish to use a different ordering.

Comparable用于具有自然排序的对象。对象本身知道如何对其进行排序。
Comparator用于没有自然排序的对象或当您希望使用不同的排序时。

回答by KLE

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 implementationwith 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) ; 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<Object>允许您在编译时在所有代码中使用它(如果需要,这很好,否则就不好,并且您会丢失编译时错误);您的实现必须处理对象,并根据需要但以健壮的方式进行转换。
  • 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 原则,并给您带来运行时错误)。

回答by SravaniChowdary.Gorijavolu

Difference between Comparator and Comparable interfaces

Comparator 和 Comparable 接口之间的区别

Comparableis used to compare itself by using with another object.

Comparable用于通过使用另一个对象来比较自身。

Comparatoris used to compare two datatypes are objects.

Comparator用于比较两种数据类型是对象。

回答by javapassion

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.

  2. Comparable in Java is used to implement natural ordering of object. In Java API String, Date and wrapper classes implement Comparable interface.

  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.

  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.

  1. 如果您看到那么这两者之间的逻辑区别是 Java 中的 Comparator 比较提供给他的两个对象,而 Comparable 接口将“this”引用与指定的对象进行比较。

  2. Java 中的 Comparable 用于实现对象的自然排序。在 Java API String、Date 和 wrapper 类中,实现了 Comparable 接口。

  3. 如果任何类在 Java 中实现了 Comparable 接口,则可以使用 Collections.sort() 或 Array.sort() 方法自动对 List 或 Array 对象的集合进行排序,并且对象将根据 CompareTo 方法定义的自然顺序进行排序。

  4. 在 Java 中实现 Comparable 的对象可以用作排序映射中的键或排序集中的元素,例如 TreeSet,无需指定任何 Comparator。

site:How to use Comparator and Comparable in Java? With example

网站:如何在 Java 中使用 Comparator 和 Comparable?举例

Read more: How to use Comparator and Comparable in Java? With example

阅读更多:如何在 Java 中使用 Comparator 和 Comparable?举例

回答by Jianmin Liu

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

单击链接以查看更多示例。相伴的

回答by Srinivas

If you see then logical difference between these two is Comparatorin Java compare two objects provided to him, while Comparableinterface compares "this" reference with the object specified.

如果你看到那么这两者之间的逻辑区别是Comparator在 Java 中比较提供给他的两个对象,而Comparable接口将“this”引用与指定的对象进行比较。

Comparablein Java is used to implement natural ordering of object. In Java API String, Date and wrapper classes implement Comparableinterface.

ComparableJava中用于实现对象的自然排序。在Java API String、Date 和wrapper 类中实现了Comparable接口。

If any class implement Comparableinterface in Java then collection of that object either Listor Arraycan be sorted automatically by using Collections.sort()or Array.sort()method and object will be sorted based on there natural order defined by compareTomethod.

如果任何类Comparable在 Java 中实现了接口,那么该对象的集合List或者Array可以通过使用Collections.sort()Array.sort()方法自动排序,并且对象将根据compareTo方法定义的自然顺序进行排序。

Objects which implement Comparablein Java can be used as keys in a sorted map or elements in a sorted set for example TreeSet, without specifying any Comparator.

例如,Comparable在 Java中实现的对象可以用作排序映射中的键或排序集中的元素TreeSet,而无需指定任何Comparator