Java:比较与比较器
可能的重复:
compare() 和compareTo() 之间的区别
Java:实现 Comparable 和 Comparator 之间有什么区别?
Comparable 和 Comparator 之间的主要区别是什么。
在什么情况下哪个比另一个更受青睐?
谢谢
更新 - 示例链接很好!!
http://www.digizol.com/2008/07/java-sorting-comparator-vs-comparable.html
Possible Duplicates:
difference between compare() and compareTo()
Java: What is the difference between implementing Comparable and Comparator?
What are the keys differences between Comparable and 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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当您的类实现 Comparable 时,
compareTo 方法定义该对象的“自然”顺序。根据合同规定,该方法有义务(尽管不是强制要求)与该对象上的其他方法保持一致,例如当
.equals()
比较返回 true 时,应始终为对象返回 0。Comparator 是它自己的定义:比较两个对象,并且可用于以可能不符合自然顺序的方式比较对象。
例如,字符串通常按字母顺序进行比较。因此,
"a".compareTo("b")
将使用字母顺序比较。如果您想比较字符串的长度,则需要编写一个自定义比较器。简而言之,没有太大区别。它们的目的都是相似的。一般来说,实现自然顺序的可比较(自然顺序定义显然可以解释),并为其他排序或比较需求编写比较器。
When your class implements Comparable, the
compareTo
method 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.A Comparator is 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.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.
Comparator
为您提供了一种为您无法控制的类型提供自定义比较逻辑的方法。Comparable
允许您指定如何比较正在实现的对象。显然,如果您无法控制某个类(或者您想提供多种方法来比较您可以控制的对象),那么请使用
Comparator
。否则,您可以使用
Comparable
。Comparator
provides a way for you to provide custom comparison logic for types that you have no control over.Comparable
allows you to specify how objects that you are implementing get compared.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
.Otherwise you can use
Comparable
.