Java : Comparable vs Comparator [英] Java : Comparable vs Comparator

查看:35
本文介绍了Java : Comparable vs Comparator的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<块引用>

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

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

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

谢谢

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

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

解决方案

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

比较器是它自己的定义了解如何比较两个对象,并可用于以可能不符合自然顺序的方式比较对象.

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

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

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

解决方案

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.

这篇关于Java : Comparable vs Comparator的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆