何时使用Comparable和Comparator [英] When to use Comparable and Comparator

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

问题描述

我有一个对象列表,我需要对一个字段进行排序,比如分数。在没有多想的情况下,我编写了一个实现Comparator的新类,它可以执行任务并且可以正常运行。

I have a list of objects I need to sort on a field, say Score. Without giving much thought I wrote a new class that implements Comparator, that does the task and it works.

现在回过头来看,我想知道我是否应该让我的类实现Comparable,而不是创建一个实现Comparator的新类。分数是对象将被订购的唯一字段。

Now looking back at this, I am wondering if I should have instead have the my class implement Comparable instead of creating a new class that implements Comparator. The score is the only field that the objects will be ordered on.


  1. 作为一种做法,我做了什么?

  1. What I have done acceptable as a practice?

正确的方法是首先让类实现Comparable(对于自然顺序),如果需要替代字段比较,那么创建一个新类,实现比较器?

Is the right approach "First have the class implement Comparable (for the natural ordering) and if an alternative field comparison is required, then create a new class that implements Comparator" ?

如果上面的(2)为真,那么它是否意味着只有在具有类实现Comparable之后才应该实现Comparator? (假设我拥有原始课程。)

If (2) above is true, then does it mean that one should implement Comparator only after they have the class implement Comparable? (Assuming I own the original class).


推荐答案

我想说的是一个对象应该实现Comparable,如果这是对类进行排序的明确自然方式,并且任何人都需要对类进行排序通常会想要这样做。

I would say that an object should implement Comparable if that is the clear natural way to sort the class, and anyone would need to sort the class would generally want to do it that way.

如果但是,排序是一个不寻常的类使用,或者排序只对特定用例有意义,然后比较器是一个更好的选择。

If, however, the sorting was an unusual use of the class, or the sorting only makes sense for a specific use case, then a Comparator is a better option.

放另一个方式,鉴于类名,是否可以比较排序,或者你是否必须求助于阅读javadoc?如果是后者,可能性是每个未来的排序用例都需要一个比较器,此时可比较的实现可能会减慢类的用户速度,而不是加速它们。

Put another way, given the class name, is it clear how a comparable would sort, or do you have to resort to reading the javadoc? If it is the latter, odds are every future sorting use case would require a comparator, at which point the implementation of comparable may slow down users of the class, not speed them up.

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

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