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

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

问题描述


可能重复:

compare()和compareTo()之间的差异

Java:实现Comparable和Comparator有什么区别?

Comparable和Comparator之间的关键区别是什么。

What are the keys differences between Comparable and Comparator.

哪种情况比其他情况更受欢迎?

and which is preferred over the other in what scenarios?

谢谢

已更新 - 与示例有良好关系!!

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

推荐答案

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

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 比较器是它自己如何比较两个对象的定义,可用于以可能与自然顺序不一致的方式比较对象。

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.

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

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天全站免登陆