Java:可比较与比较器

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

Java : Comparable vs Comparator

javacomparatorcomparable

提问by daydreamer

Possible Duplicates:
difference between compare() and compareTo()
Java: What is the difference between implementing Comparable and Comparator?

可能的重复项:
compare() 和 compareTo()
之间的区别 Java:实现 Comparable 和 Comparator 之间有什么区别?

What are the keys differences between Comparable and Comparator.

Comparable 和 Comparator 之间的主要区别是什么。

and which is preferred over the other in what scenarios?

在什么情况下哪个比另一个更受欢迎?

Thanks

谢谢

Updated - GOOD LINK WITH EXAMPLE!!

更新 - 与示例的良好链接!!

http://www.digizol.com/2008/07/java-sorting-comparator-vs-comparable.html

http://www.digizol.com/2008/07/java-sorting-comparator-vs-comparable.html

采纳答案by Andy

When your class implements Comparable, the compareTomethod of the class is defining the "natural" ordering of that object. That method is contractually obligated (though not demanded) to be in line with other methods on that object, such as a 0 should always be returned for objects when the .equals()comparisons return true.

当您的类实现Comparable 时,类的compareTo方法正在定义该对象的“自然”排序。该方法在合同上有义务(尽管不是强制要求)与该对象上的其他方法保持一致,例如当.equals()比较返回 true时,应始终为对象返回 0 。

A Comparatoris its own definition of how to compare two objects, and can be used to compare objects in a way that might not align with the natural ordering.

一个比较本身就是如何比较两个对象的定义,可用于可能不与自然顺序排列的方式来比较的对象。

For example, Strings are generally compared alphabetically. Thus the "a".compareTo("b")would use alphabetical comparisons. If you wanted to compare Strings on length, you would need to write a custom comparator.

例如,字符串通常按字母顺序进行比较。因此"a".compareTo("b")将使用字母顺序比较。如果您想比较字符串的长度,则需要编写一个自定义比较器。

In short, there isn't much difference. They are both ends to similar means. In general implement comparable for natural order, (natural order definition is obviously open to interpretation), and write a comparator for other sorting or comparison needs.

简而言之,没有太大区别。它们都是相似手段的目的。一般实现可比对自然顺序,(自然顺序定义显然可以解释),并为其他排序或比较需求编写比较器。

回答by Justin Niessner

Comparatorprovides a way for you to provide custom comparison logic for types that you have no control over.

Comparator为您提供了一种为您无法控制的类型提供自定义比较逻辑的方法。

Comparableallows you to specify how objects that you are implementing get compared.

Comparable允许您指定您正在实现的对象如何进行比较。

Obviously, if you don't have control over a class (or you want to provide multiple ways to compare objects that you do have control over) then use Comparator.

显然,如果您无法控制一个类(或者您想提供多种方法来比较您可以控制的对象),那么使用Comparator.

Otherwise you can use Comparable.

否则,您可以使用Comparable.